Conceptually Oracle is a Kernel package that has a number of tools that can be purchased separately and integrated with the kernel as “Addons”. These tools allows the user to create data base objects, forms, reports, graphs etc. Some of the tools of Oracle are SQL *Plus, Oracle Forms, Oracle Report Writer, Oracle Graphics, SQL Precompiler for C & Cobol.


Oracle DBA : The Oracle DBA can compile and execute SQL Sentences issued by a user.
SQL *Plus : It is made up of two parts : i) Interactive SQL ii) PL / SQL It is an oracle specific program which accepts SQL commands and PL/SQL blocks and executes them. PL/SQL is Extension of SQL. It can contain any number of SQL statements integrated with the flow of control statements.

Allows us to create a data entry screen.   Oracle Graphics : Using this tool data can be represented in the form of graphs. Reports : It is an application development tool of oracle for developing displaying and printing reports. . Forms : This is a graphical tool used for generating and executing forms based applications.


 Language is used by most of the database management systems to unable users to access data.  This is the natural language of Oracle DBA.  ANSI has accepted SQL has become a standard language for RDBMS.  It is developed by IBM in 1970s.INTRODUCTION TO SQL Structured Query Language is a standard command set used to communicate with the RDBMS.  .

 SQL is non-procedural language.  .FEATURES OF SQL SQL is English Like Language.  Creating and manipulating database objects.  Controlling access to the databases objects for security  Ensure database security.  SQL commands sets can be used by administrators.  SQL can be used for variety of tasks.  Querying data stored in the tables. developers and end users alike for their varying requirements.  Manipulating data stored in database.

Delete DCL (Data Control Language) Grant. Revoke. Savepoint   . Drop. Alter.SQL SQL is broadly divided into three categories :  DDL (Data Definition Language) Create. Insert. Truncate DML (Data Manipulation Language) Select. Commit. Update. Rollback.

 You are prompted for your Login id and Password. Click on Oracle and then select SQL *Plus. and SQL> prompt appears. It displays a list of programs. Now you can start to write SQL Commands or SQL statements.INVOKING SQL *PLUS Start windows in normal way.  .  Once Login id and password is entered.  Now you are connected to Oracle DBA.  Click on Start button and click on Programs.

Guidelines for Writing SQL Commands An SQL command is entered at the SQL *Plus prompt.) 2) Slash (/) 3) Blank Line .  Word delimiter is a space or a tab.  SQL commands may be one line or several lines.  Most recent SQL or PL/SQL command is stored in SQL buffer.  Command entry can be in upper or lower case.  SQL commands can be terminated by  1) Semicolon (.  Buffer command can be edited or re-executed.

-Select Ename.-Select * from emp.SELECT Statements  Simplest form of SELECT Statement contains SELECT clause  FROM clause e.g.g. DeptNo from Emp.  .  Specifying column headers (Column Aliases)  Concatenation operator  Handling NULL values  Eliminating duplicate values. e.

1.Selected Columns and All Rows: SELECT columname. .AllRows and all column:  SELECT * FROM tablename.SELECT Statements Simplest form of SELECT Statement contains  The „SELECT‟ SQL verb is used to view the table data.Selected Rows and All Columns: SELECT * FROM tablename WHERE search condition.columname FROM tablename. 3. SELECT columnname. 2.columnname FROM tablename WHERE search condition.

columname [sort order]. SELECT DISTINCT columnname. columname FROM tablename . 4.3. .Sorting data in a table: SELECT * FROM tablename ORDER BY columnname.Elimination of duplicates from the Select statement: SELECT DISTINCT * FROM tablename.

SELECT Statements  Sorting query results (ORDER BY clause) Data results are presented in a sorted order (ascending or descending) according to the value of the column specified with ORDER BY clause.  .  ASC and DESC.  ORDER BY clause should be the last clause in SELECT statement.  When data is sorted in the ascending order NULL values appears at the end in sorted column.  More than one column can be used to query result.

A comparison operator. if used.  Condition specified with WHERE clause acts as a filter and returns only those rows that satisfy the condition. literal or list of values.SELECT Statements  Both DISTINCT and ORDER BY clause can not be used with SELECT statement.  WHERE clause :  Used with SELECT statement to retrieve selected row from a table.  WHERE clause must follow the FROM clause. .  Condition specified after WHERE clause contains: A column name.

END1 .

Represents date and time in table in fixed length in 7 bytes. The default width is 1 and maximum width is 255 characters. . Number Represents the floating point number with 38 significant digits precision. Number (p. Varchar2 (size) Represents fixed length characters up to the width size. The maximum width is 2000 characters.ORACLE DATA TYPES Data Type Char (size) Description Represents fixed length characters up to the width size. Default format is „dd-mm-yyy‟.s) Date Represents numbers with precision of size „p‟ and numbers of digits after the decimal is „s‟. Number (Size) Represents integers of precision size.

Can not contain character sets of varying widths. Long Raw CLOB Used to store binary data of variable length. Used to store file pointers to LOBs managed by file systems external to the database. Table can have multiple columns. Only one column is allowed per table. which can have a maximum size off 2 GB. BLOB BFILE Used to store large binary objects such as graphics video clips and sound files. Used to store byte oriented data like binary data or byte strings and the maximum size is 2000 bytes. Used to store character object with single byte characters. Table can have multiple columns with CLOB data type.ORACLE DATA TYPES Data Type Long Raw Description Represents the variable length characters up to 2 GB. .

DATA DEFINITION LANGUAGE (DDL)  DDL is a set of SQL commands used to create.  DDL commands Create  Alter  Drop  Truncate  . modify or remove various database objects such as table views. synonyms etc.

CREATING TABLES Creating Table :  CREATE TABLE statement : Syntax : CREATE TABLE <tablename> (column_name data_type (size).g. roll_no number (3).). . CREATE TABLE student (sr_no number(2). name varchar2(20).   E. column_name data_type(size) …. address varchar2(50)).

. Note :      When you supply values to all columns it is not necessary to have column list. Can be used a substitution variables to insert rows.INSERTING VALUES IN THE TABLE   INSERT statement : Syntax : INSERT INTO <tablename> (column. When to supply values to specific columns. One INSERT command add one row to a table at a time unless a subquery is used. it is mandatory to have a column list. value …). column…) VALUES (value. Date and character columns are required to be enclosed in a single quotes.

DELETE OPERATIONS  The verb DELETE in SQL is used to remove rows from table.   . To remove All the rows from a table or A select set of rows from a table. REMOVAL OF ALL ROWS : Syntax : DELETE FROM <tablename>. REMOVAL OF A SPECIFIED ROW/S Syntax : DELETE FROM <tablename> WHERE search condition.

RENAMING TABLES  To rename a table. . the syntax is : Syntax : RENAME oldtablename TO newtablename DESTROYING TABLES  To destroy the table. the Syntax is : Syntax : DROP TABLE <tablename>.

End2 .

Finding out the column details of a table created : To find information about the columns defined in the table use the following syntax : Syntax : DESCRIBE <tablename>. The objects name and type are displayed.EXAMINING OBJECTS CREATED BY A USER  Finding out the table/s created by a user : To determine which tables the user has access to the syntax is : SELECT * FROM TAB.  .

columnname = expression). UPDATING RECORDS CONDITIONALLY : Syntax : UPDATE <tablename> SET (columnname = expression.  .  UPDATING OF ALL ROWS : Syntax : UPDATE <tablename> SET (columnname = expression.UPDATING THE CONTENTS OF A TABLE  The update command is used to change or modify data values in a table. To update All the rows from a table OR A select set of rows from a table. columnname = expression) WHERE columnname = expression.

MODIFYING THE STRUCTURE OF TABLE  ADDING NEW COLUMNS : Syntax : ALTER TABLE <tablename> ADD (newcolumnname datatype(size). .…….).  MODIFYING EXISTING COLUMNS : Syntax : ALTER TABLE <tablename> MODIFY (columnname newdatatype (newsize)).

 Decrease the size of a column if table data exists. Change the name of the table.  .  Drop a column.  Change the name of the column. RESTRICTIONS ON THE ALTER TABLE : Using the ALTER TABLE clause the following tasks cannot be performed.

END3 .

e. The Target table is one identified in the „CREATE‟ section of the SQL sentence. columnname) AS SELECT columnname. The condition specified in the where clause must not be satisfied. This SQL sentence populates the Target table with data from the Source Table. . columnname FROM <tablename>. create the structure only).   To create a Target table without the records from the source table (i.CREATING A TABLE FROM A TABLE  Syntax : CREATE TABLE <tablename> (columnname. the select statement used will have a „where clause‟. The Source table is the table identified in the „SELECT‟ section of the SQL sentence. This means the select statement in the CREATE TABLE definition must not retrieve any rows.

Insertion of a data set into a table from another table : INSERT INTO <tablename> SELECT columnname. columnname FROM <tablename> WHERE columnname = expression . columnname FROM <tablename>.INSERTING DATA INTO A TABE FROM ANOTHER TABLE  In addition to inserting data one row at a time into a table. it is quite possible to populate a table with data that already exists in another table. The syntax for this is : Syntax : INSERT INTO <tablename> SELECT columnname.  .

OPERATORS Operator + (Addition) .(Subtraction) * (Multiplication) Arithmetic Operators Description / (Division) = (Equal to) > (Greater Than) >= (Greater Than or Equal To) < (Less Than) Logical Operators <= (Less Than or Equal To) .

LOGICAL OPERATORS  The AND Operator : The Oracle engine will process all rows in a table and display the result only when all of the conditions specified using the AND operator are satisfied. e. .g.SELECT product_no. description. profit_percent FROM product_master WHERE profit_percent >=10 AND profit_percent <=20.

g. The OR Operator : The Oracle engine will process all rows in a table and display the result only when any of the conditions specified using the OR operator are satisfied. address2. city. address1. name.SELECT clinet_no. e. . pincode FROM client_master WHERE (pincode =400054 OR pincode = 400057.

 The NOT Operator : The Oracle engine will process all rows in a table and display the result only when none of the conditions specified using the NOT operator are satisfied. pincode FROM client_master WHERE NOT (city = „Bombay‟ or city = „Delhi‟). address1. city.- . name. SELECT clinet_no. e. address2.g.

the BETWEEN operator is used.RANGE SEARCHING In order to select data that is within a range of values. . The two values in between the range must be linked with the keyword AND. one cannot mix the data types i. The lower value must be coded first. However. The BETWEEN operator allows the selection of rows that contain values within a specified lower and upper limit.e. the lower value of a range of values from a character column and the other from a numeric column. A BETWEEN operator can be used with both character and numeric data types. The range coded after the word BETWEEN is inclusive.

description. profit_percent.sell_price FROM product_master WHERE profit_percent BETWEEN 10 AND 20. E.g: SELECT product_no. .

The LIKE predicate allows for a comparison of one string value with another string value. Two wildcard characters that are available are : For character : data types The percent sign (%) matches any string The Underscore ( _ ) matches any single character. . Such a precision may not always be desired or necessary. which is not identical. For this purpose Oracle provides a predicate LIKE.PATTERN MATCHING  The use of the LIKE predicate : The comparison operator discussed so far have compared one value. This is achieved by using wildcard characters. exactly to one other value.

: SELECT * FROM supplier_master WHERE supplier_name LIKE „_r%‟ OR supplier_name LIKE „_h%‟.: SELECT * FROM supplier_master WHERE supplier_name LIKE „ja%‟.1) Retrieve all information about suppliers whose names begin with the letters „ja‟ from supplier_master.  E. 2) Retrieve all information about suppliers where the second character of names are either „r‟ or „h‟.  E.g. .g.

This will select all the rows where values do not match all of the values in the list. . The NOT IN predicate is the opposite of the IN predicate. One can check a single value against multiple values by using the IN predicate. The IN and NOT IN predicates : The arithmetic operator ( = ) compares a single value to another single value. In case a value needs to be compared to a list of values then the IN predicate is used.

city and pincode from the table supplier_master where the supplier_name is either Ramos or Clark or Pramada . ‟Clark‟. .address1.: SELECT supplier_name.: SELECT supplier_name. address1.address1. ‟Pramada‟). city.address2.1) Retrieve the supplier_name. ‟Clark‟.address2.  E. city.g. ‟Pramada‟).address2. pincode FROM supplier_master WHERE supplier_name IN („Ramos‟. 2) NOT IN  E.g. pincode FROM supplier_master WHERE supplier_name NOT IN („Ramos‟.

g. e. However. and contains the value x in that column. To facilitate such calculations via a SELECT. otherwise the SELECT fails.THE ORACLE TABLE ‘DUAL’ Dual is a small Oracle worktable. Besides arithmetic calculations. 2*2. . a SELECT must have a table name in its FROM clause. When an arithmetic exercise is to be performed such as 2*2 or 4/2 etc. Often a simple calculation needs to be done. there really is no table being referenced. which consists of only one row and one column. against which SELECT statement that are required to manipulate numeric literals can be fired and output obtained. only numeric literals are being used. it also supports date retrieval and it‟s formatting. The only SQL verb to cause an output to be written to a VDU screen is SELECT. Oracle provides a dummy table called DUAL.

Output : 2*2 ------4 The current date can be obtained from the table DUAL in the required format as shown below : SYSDATE : Sysdate is a pseudo column that contains date and time. Output : SYSDATE -------------18-FEB-82 . Example : SQL> SELECT sysdate FROM dual. It requires no arguments when selected from the table DUAL and returns the current date.Example : SQL> SELECT 2 * 2 FROM dual.

END4 .


Returns char1 right padded to length n with the sequence of characters in char2.char2) LTRIM (char. set) Description Returns char. Removes characters from the left of char with initial characters removed upto the first character not in set. Returns a portion of char. with all letters in upper case. m.CHARACTER FUNCTIONS Function LOWER (char) UPPER (char) INITCAP (char) CONCAT (char1.char2) RPAD (char1. Returns char after final characters removed after the last character not in set. Returns char. . set) RTRIM (char.char2) SUBSTR (char.n. Joins char1 and char2 values in the output. n) LPAD (char1.n. with all letters in lower case. Returns string with the first letter in upper case. beginning at character „m‟ exceeding upto „n‟ characters. Returns char1 left padded to length n with the sequence of characters in char2.

10.Function Lower Upper Initcap Substr Lenghth Syntax SELECT LOWER („IVAN BAYROSS‟) “LOWER” FROM Dual.‟N‟) “Left trim example” FROM Dual. SELECT LENGTH („IVAN BAYROSS‟) “LENGTH” FROM Dual. SELECT RTRIM („NISHA‟.‟Patil‟) “Concat” FROM Dual. . SELECT LPAD („Page 1‟.4) “Substring” FROM Dual. Carol‟) FROM Dual.‟x‟) “Rpad” FROM client1_master Where name= „TURNER‟. SELECT INITCAP („IVAN BAYROSS‟) “Title Case” FROM Dual. SELECT SUBSTR („BAYROSS‟.‟*‟) “Lpad” FROM Dual. SELECT CONCAT(„Rohan‟. Ltrim Rtrim Lpad Rpad Concat SELECT LTRIM („NISHA‟. SELECT UPPER („Mr.3. SELECT RPAD ( name.‟10‟.‟A‟) “Right trim example” FROM Dual.

END5 .

. if m is omitted then n is rounded to 0. n) SQRT (n) EXP (n) SIGN (n) Returns smallest integer that is greater than or equal to n Returns n rounded to m places right of the decimal point. Returns e raised to the nth power. m) MOD (m. n) TRUNC (n.NUMBER FUNCTIONS Function ABS (n) Description Returns the absolute value of n. the function returns -1. Returns the square root of n. if n>0 the function returns 1. if n=0 the function returns 0. Returns the remainder of m divided of m divided by n. Returns m raised to the nth power. Returns n truncated to m decimal places if m is omitted to 0 places. CEIL (n) ROUND (n. m) POWER (m. If n<0.

Function Syntax ABS POWER ROUND SQRT CEIL MOD TRUNC EXP FLOOR SELECT ABS(-15) “Absolute” FROM dual. SELECT FLOOR(12) “FLOOR” FROM dual. SELECT ROUND(15. SELECT EXP(2) “EXP” FROM dual.1) “Round” FROM dual. SIGN SELECT SIGN(-2) “SIGN” FROM dual. SELECT CEIL(5) “CEIL” FROM dual. SELECT TRUNC(12. .19. SELECT MOD(12.10) “MOD” FROM dual.2) “Raised” FROM dual. SELECT POWER(3.3) “MOD” FROM dual. SELECT SQRT(25) “Square Root” FROM dual.

d2) ADD_MONTHS (d. . char) Description Returns today‟s date. n) LAST_DAY (d) NEXT_DAY (d.DATE FUNCTIONS Function SYSDATE MONTHS_BETWEEN (d1. The argument char may be number representing a day or a character string. Returns number of months between d1 and d2. Returns the date d plus n months. Returns the date of the last day of the month that contains d. Returns the date of the first weekday named by char that is later than the date d.


TIME FUNCTION NEW_TIME (date. „this‟. „other‟) : Gives the date (and time) in this time zone. Time zones are as follows : AST/ADT : Atlantic Standard / daylight Time BST/BDT : Bering Standard / daylight Time CST/CDT : Central Standard / daylight Time EST/EDT : Eastern Standard / daylight Time GST : Greenwich Mean Time HST/HDT : Alaska-Hawaii Standard / daylight Time MST/MDT : Mountain Standard / daylight Time NST : Newfoundland Standard Time PST/PDT : Pacific Standard / daylight Time YST/YDT : Yukon Standard / daylight Time  . other will be replaced by a three-letter abbreviation for the other time zone for which you‟d like to know the time and date. this will be replaced by a three-letter abbreviation for the current time zone.

END6 .

Function TO_CHAR (n, fmt) TO_CHAR (n, fmt) TO_DATE (char, fmt) ASCII (char) CHR (num) Description Converts the value of NUMBER datatype to a value of CHAR datatype using optional format string. Converts the value of DATE datatype to a CHAR value. Converts the character value representing date into a date value according to the fmt specified. Returns ASCII value of char. Returns ASCII character of num.



  

Processes multiple rows of a table and group them based on a condition. Group functions return only a single row as the result of grouping the rows. Important notes :
   

Where clause can used to restrict the input of rows for group formation. Group functions cannot be used with where clause. Can be used multiple column name in the group by clause. All group functions except COUNT (*) ignore nulls. Columns not taking part in the group functions cannot appear in the SELECT column list. They can appear in the select column-list only if they are part of GROUP BY clause.

GROUP FUNCTIONS Function Description AVG (expr) COUNT (expr) Returns average value. Returns minimum value of expr. Returns number of rows in the query MAX (expr) MIN (expr) SUM (expr) Returns maximum value of expr. . Returns sum of values of expr.

SELECT MAX(bal_due) “Maximum Balance” FROM CLIENT_MASTER SELECT SUM(bal_due) “Total Balance Due” FROM CLIENT_MASTER .Function AVG COUNT MIN MAX SUM Syntax SELECT AVG(sell_price) “Average” FROM PRODUCT_MASTER Select count(empno) “No of Employees” FROM EMP. SELECT MIN(bal_due) “Minimum Balance” FROM CLIENT_MASTER.

HAVING CLAUSE Having clause is used to restrict the display of grouped rows.  Important notes :  The WHERE clause can still be used to consider the specific set of rows.  The result of the grouped query is passed on to the HAVING clause for output filtration.  The HAVING clause restricts the output and can only be used when the GROUP BY clause is part of query.  .  The WHERE clause restricts the input before grouping  The WHERE clause can not use group functions.


END7 .

Advantages of Integrity Constraints :     Do not have to program applications to check for the validity of data.CONSTRAINTS        Rules which are enforced on data being entered. Helps to enforce business rules on data. and prevents the user from entering invalid data into tables are called „Constraints‟. Oracle permits data constraints to be attached to table columns via SQL syntax that will check data for integrity. Once define an integrity constraint for a table all program using that table can benefit from it. When business rule change constraint can be modified centrally. Even if single column of the record being entered into the table fails a constraint. . constraints super control data being entered in tables for permanent storage. Always conforms to the rule specified by the integrity constraints. Are easy to specify and maintain. Thus. entire record is rejected and not stored in the table.

Types of Integrity Constraints  Entity Integrity Constraints :  Ensure that each row in a table is unique.  Referential Integrity Constraints : These constraints ensure that the values in a column of a table match the values in a related column of another table.   Integrity constraints can be applied at two levels : Table Constraints  Column Constraints  .  Enforce the business rules across more than one table in a database.

then that column becomes a mandatory column. the Oracle engine will automatically load this column with the default value. .Entity Integrity Constraints  DEFAULT constraint :   At the time of table creation a „default value‟ can be assigned to a column. When the user is loading a „record‟ with values and leaves this column empty.  NOT NULL constraint :   When a column is defined as not null . Create Table <table name> (column_name data_type (size) [DEFAULT default_value] [NOT NULL] ………). Create Table <table name> (column_name data_type (size) [DEFAULT default_value]………). It implies that a value must be entered into the column if the record is to be accepted for storage in table.

address1 varchar2(30) NOT NULL.g:CREATE TABLE cilent_master (client_no varchar2(6) NOT NULL. state varchar2(15). remarks varchar2(60). name varchar2(20) NOT NULL. bal_due number(10.e. address2 varchar2(30) NOT NULL.2)). pincode number(6). city varchar2(15). .

address2 varchar2(30).2)).Entity Integrity Constraints  UNIQUE constraint : The purpose of a unique key is to be ensure that information in the column(s) is unique. city varchar2(15). state varchar2(15).  Create Table <table name> (column_name data_type (size) …… UNIQUE (column_name.  . name varchar2(20). column_name……)). remarks varchar2(60). e.  Create Table <table name> (column_name data_type (size) UNIQUE). pincode number(6). address1 varchar2(30).g:CREATE TABLE clinet_master (client_no varchar2(6) UNIQUE.bal_due number(10.

address2 varchar2(30). state varchar2(15). city varchar2(15) CHECK (city IN („Delhi‟. name varchar2(20) CHECK(name=upper(name)).g: CREATE TABLE client_master (clinet_no varchar2(6) CHECK(client_no like „C%‟).  Create Table <table name> (column_name data_type (size) …… CHECK (condition).2)). e. bal_due number(10. remarks varchar2(60).‟Calcutta‟. address1 varchar2(30).‟Madras‟)). . CHECK Constraint : Business rule validations can be applied to a table by using CHECK constraint.  Create Table <table name> (column_name data_type (size) CHECK (condition)……).‟Bombay‟. pincode number(6).

The NOT NULL attribute is active.…………). column_name.……). Create Table <table name> (column_name data_type (size) …… PRIMARY KEY (column_name.e.  A single column primary key is called Simple key.Referential Integrity Constraints  PRIMARY KEY constraint :  Primary Key is one or more column(s) in a table used to uniquely identify each row in the table. A Primary Key column in a table has special attributes :   It defines the column as mandatory column i. A multicolumn primary key is called a composite primary key. The data held across the column must be UNIQUE.   . the column cannot be left blank. Create Table <table name> (column_name data_type (size) PRIMARY KEY.

column. The table in which the foreign key is defined is called a Foreign Table or Detail Table. Oracle references the primary key. Create Table <table name> (column_name data_type (size) REFERENCES table_name (column.………) . A foreign key is a column (or a group of columns) whose values are derived from the primary key or unique key of some other table. The master table can be referenced in the foreign key definition by using the REFERENCES adverb.…) REFERENCES table_name (column. by default.…… FOREIGN KEY (column. The table that defines the primary or unique key and is referenced by the foreign key is called the Primary Table or Master Table.……). If the name of column is not specified. Create Table <table name> (column_name data_type (size).Referential Integrity Constraints  FOREIGN KEY constraint :      Foreign key represents relationship between tables. column. .

END8 .

.Defining Integrity Constraints in the Alter table command    You can also define integrity constraints. using the constraint clause.g:ALTER TABLE supplier_master ADD Primary Key (supplier_no). in the ALTER TABLE command. Syntax : ADD : ALTER TABLE <tablename> ADD <constraint_definition> e.

 MODIFY : ALTER TABLE <tablename> MODIFY <constraint_definition> e. .g:ALTER TABLE sales_order_details ADD constraint order_fkey Foreign Key (detlorder_no) References sales_order Modify (qty_ordered number(8) Not Null).

g:ALTER TABLE supplier_master Drop Primary Key. . DROP : ALTER TABLE <tablename> DROP <constraint_definition> e.g:ALTER TABLE sales_order_details Drop Constraint fk_prno. e.

The convention used by Oracle is : SYS_Cn where n is a numeric value that makes the constraint name unique. A constraint can be dropped by referring to the constraint by its name.Assigning User Defined Name to Constraints    When constraints are defined. Under this circumsta-nces a user defined constraint name becomes very convenient. Hence user named constraints simplifies the task of dropping constraints. it becomes difficult to search for and identify the required constraint to be dropped. If Oracle generated names are to be used. . Constraint can be given user defined name along with the constraint definition. Oracle assigns a unique name to each constraint.

 . bal_due number(10. city varchar2(10). pincode number(8). address2 varchar2(15). name varchar2(25).2)). address1 varchar2(15).  The syntax is : CONSTRAINT<constraintname> <constraintdefinition> e.g:CREATE TABLE client_master (client_no varchar2(6) CONSTRAINT p_clientkey PRIMARY KEY.Assigning User Defined Name to Constraints A constraint can be given a user-defined name by preceding the constraint definition with the reserve word CONSTRAINT and a user-defined name.

Assignment  Create a sales_order_details table where : Date Type varchar2 Size 6 Attributes Primary Key. . Column Name detlorder_no proederoduct_no varchar2 6 qty_ordered qty_disp number number 8 8 product_rate number 8.2 Not null. Foreign Key references product_no of product_master table. Primary Key. Cannot be greater than qty_ordered. Foreign Key references or order_no of sales_order table.

END9 .

. used with SELECT. The statement containing a subquery is called a parent query. To update records in a target table. IN etc.Subqueries  A subquery is form of an SQL statement that appears inside another SQL statement. To provide values for conditions in WHERE.  It can be used by the following commands :      To insert records in a target table. UPDATE and DELETE statements. To create tables and insert records in the table created. It is also termed as nested query. To create views. The parent query statement uses the rows returned by the subquery. HAVING.

Subqueries  A format of subquery can be as under :  SELECT column1. . column2 from <tablename> WHERE column = (SELECT column FROM <tablename> WHERE condition) .  e.g:Select * from sales_order Where client_no = (select client_no from client_master Where name=„Rahul Desai‟).

 Types  of Subqueries : Single Row Subqueries  Multiple Value Subqueries  Multiple Column Subqueries  Co-related Subqueries .

 .g. Write a query to find out names of employees who earn less than the average salary.  Solution : SELECT ename FROM emp WHERE sal < (SELECT avg (sal) FROM emp).  The subquery result is then compared to the value of the column (s) in the parent statement.  E.Single Row Subqueries Single row subqueries returns a single value from a table.

 The subquery result is then compared to the value the columns in the parent statements.Multiple Value Subqueries Multiple value subqueries returns more than one value to the parent query statements from a table.  Solution :  SELECT ename FROM emp WHERE sal IN (SELECT max (sal) FROM emp GROUP BY job).g.  E.  . Write a query to find out names of employees who earn maximum salary in each job.

job.Multiple Column Subqueries      Multiple column subqueries return values from more than one column.g. Solution : SELECT ename. E. The subquery result is then compared to the value of the column (s) in the parent statement. . job FROM emp GROUP BY job). sal FROM emp WHERE (sal. job) IN (SELECT max (sal). Write a query to find out names of employees who earn maximum salary in each job.

Solution : SELECT job. .Subqueries in Having Clause   Write a query to find out jobs having the salary less than the average salary of ANALYST. avg (sal) FROM emp GROUP BY job HAVING avg (sal) < (SELECT avg (sal) FROM emp WHERE job = „ANALYST‟).

Subqueries are executed from the innermost to the outermost subqueries except in the case of correlated subqueries.Subqueries  A Subquery is a SELECT statement that has a result which is utilized by another SQL statement. The ORDER BY clause can be used once with the outermost query and it should be the last clause of that SELECT statement. Points to remember :      The limit to level of nesting is 255 subqueries. . The inner query must be enclosed in parentheses and must be on right hand side of the condition that uses its result.

Sol : select ename. .job).   E. job.g. Execute the inner query using the rows value. Behaviour of a correlated subqueryis evaluated as follows:     Get a row from outer query. Write a query to find out employees who earn salary less than the average salary for their jobs.Correlated Subqueries   In correlated subqueries the inner query is evaluated repeatedly for each row in the result set of the parent query. Continue step 1 to 3 until no row from the outer query remains. sal from emp e where sal < (select avg (sal) from emp where job = e. Use the value resulting from the inner query to qualify or disqualify the row fetched from the outer query.

. Sol : Select ename1. dept_no from emp where dept_no IN (Select dept_no from emp where ename = „Amol‟) AND ename IN (Select ename from inv_sys).

END10 .


Equi – Join Non – Equi – Join Outer Join Self Join  Types of Joins :     . Join   To retrieve data multi-table queries create a join between two or more tables. A join compares data in the specified. and retrieve the rows according to the result of data comparisons.Multi-Table Queries   Use to retrieve data from more than one table using single query.

<. E. E. Select E.Deptno. E.Dname. Dept D Where E.Name.) to reference columns. S.  Non Equi-join :   A non equi-join specifies the relationship between columns belonging to different tables by making use of the relational operator (>. D.Hisal .Mgr. .Deptno From Emp E. >=.Sal.Deptno. Salgrade S Where E. E.Equi – Join  Equi-join :    Joins based on an equality condition specified with the WHERE clause in the SELECT statement.g. Must prefix the column names with the table names followed by a period (.Deptno = D. D.Ename.g.Sal And S. < >) other than = .Salgrade From Emp E. Select E. E.Sal Between S. <=.

Ename “Manager”.Empno. Select Ename.Deptno . E.Ename “Employee”. Select E. Dept D Where E.g. From Emp E.Mgr = M. M.g.Deptno (+) = D. Use an outer join operator (+) with the column of the table from which you want to retrieve only the matching rows.  Self Join:    . Join that compares values in a single column of one table are called self join. Write a query to retrieve the names of all employees and their managers. Dname. Emp M. From Emp E. Write a query to retrieve employee names and their respective department names and department name for which no person is employed. E. Outer Join :     Outer join returns matching rows from both the tables and all the rows from one of the tables specified in the join. Where E.

Set Operators  UNION Operator :  UNION operator combines the result of two queries and returns distinct rows selected by either query.  UNION ALL Operator :   INTERSECT Operator :   MINUS Operator :  . UNION ALL operator displays all rows retrieve by both the queries. Duplicate values also appear in the query result. MINUS operator retrieve all rows selected by the first query that are not in the second query. INTERSECT operator is used to retrieve rows that are common in the result set of two or more queries.

END11 .


Update. Allow users to make simple queries to retrieve the results from complicated queries i. They isolate applications from changes in definition of base tables . Show the same data to different users in different ways.VIEW    A view is a query that retrieves limited data derived from one or more tables in a database.   Create or Replace View <view_name> AS Select Statement . Delete and Drop operations can be performed on views as like Table. . Advantages of using VIEW :     Restricts access to a table or tables. Unlike table view does not physically exists in a database and does not occupy storage. they hide data complexity.e. Insert.

address2.     Create: Create View vv_sales AS select * from salesman_master. it can be queried exactly like a base table. Renaming: The columns of the view can take on different names from the table columns. state from client_master. columnname from viewname.‟DELHI‟). city.address2 add2. if required. Create View vv_clientadmin AS Select name. E. Drop View: Drop View viewname.state from vv_clientadmin Where city IN („BOMBAY‟.address1 add1. name.address1. Select columname. . Select a data set from view: Once a view has been created.

  Users can do DML operations on synonym but cannot perform DDL operations except dropping the synonym. view or sequence. . which is used as an alias (alternative name) for a table. Hide the name and owner of the object.Synonym   A Synonym is a database object. Syntax : CREATE SYNONYM <synonym_name> FOR <table_name>. They are used to :   Simplify SQL statements.

MAXVALUE integervalue / NO MAXVALUE MINVALUE integervalue / NOMINVALUE CYCLE/NOCYCLE.   Create Sequence order_seq Increment By 1 Start with 1 Maxvalue 10 Minvalue 1 Cycle Cache 4. sequential integer values. CACHE / NOCACHE. NEXTVAL. A sequence can be in an either ascending or descending order. which can generate unique. Syntax : CREATE SEQUENCE <sequence_name> INCREMENT BY integervalue START WITH integervalue.CURRVAL.Sequences     A sequence is a database object. . Seq. Seq. It can be used to automatically generate primary key values.

Select sequence_name.nextval from dual;  E.g-Insert into sales_order (order_no,order_date,client_no) values (order_seq.nextval,sysdate,‟C00001‟);  Select sequence_name.currval from dual;  Alter :Alter sequence order_seq Increment by 2 Cache 30;  Drop : Drop sequence sequnce_name; Drop sequence order_seq;

Keywords & Parameters


Specifies the interval between sequence numbers. It can be any positive or negative value but not zero. If this clause is omitted, the default value is 1. Specifies the sequence minimum value. Specifies a minimum value 1 for an ascending sequence or -(10)^26 for a descending sequence.

 



 


Specifies a maximum value that a sequence can generate.
Specifies a maximum of 10^27 for an ascending sequence or -1 for a descending sequence. This is the default clause.



Specifies the first sequence number to be generated. The default for an ascending sequence is the sequence minimum value (1) and for a descending sequence, it is the maximum values (-1). Specifies that the sequence continues to generate repeat values after reaching either its maximum value. Specifies that a sequence cannot generate more values after reaching the maximum value.
Specifies how many values of a sequence ORACLE pre-allocates and keeps in memory for faster access. The minimum value for this parameter is two.




This is only necessary if you are using Parallel Server in Parallel mode option. .  NOORDER :  This does not guarantee sequence numbers are generated in order of request. NOCACHE :  Specifies that values of a sequence are not pre-allocated. If the ORDER / NOORDER clause is omitted.  ORDER :  This guarantees that sequence numbers are generated in the order of request. a sequence always generates numbers in order. a sequence takes the NOORDR clause by default. This is only necessary if you are using Parallel server in Parallel mode option. In exclusive mode option.

DBA Role :  DBA Role has all system privileges – including unlimited space quotas – and the ability to grant all privileges to other users. .Introduction to DBA (Database Administrator)   DBA refers to the person who is the database administrator and has the DBA role.  SYSTEM is for use by a DBA user. Some of the rights that are reserved for the dba are never given to. normal users. while DBA refers just to those privileges encompassed by the DBA role. or needed by.

The SYS user owns the core internal tables Oracle uses to manage the database.Creating User      The oracle system comes with many users already created. Format for creating user : CREATE USER user_name IDENTIFIED BY password. CREATE USER Disha IDENTIFIED BY Computer. E. You can log on to the SYSTEM user and MANAGER as password to create other users.g. including SYSTEM and SYS. SYSTEM owns additional tables and views. . since SYSTEM has that privilege.

If a user wishes to access any of the objects belonging to another user. The rights that allow the use of some or all of Oracle‟s resources on the server are called Privileges. Objects that are created by a user are owned and controlled by that user. the owner of the object will have to give permission for such access. appropriate rights on Oracle‟s resources can be assigned to the user. Privileges once given can be taken back by the owner of the object.Granting & Revoking Permissions  Depending on a user‟s status and responsibility. This is called Revoking of Privileges.   . This is called Granting of Privileges.

g. The user can grant all the privileges or grant only specific object privileges. . Syntax : GRANT {ALL | object privileges} ON object_name TO user_name [WITH GRNAT OPTION]. UPDATE ON bonus TO passion. E.  Object Privileges :  Each object privilege that is granted authorizes the grantee to perform some operation on the object. GRANT SELECT. views and sequences. GRANT Statement :     The Grant statement provides various types of access to database objects such as tables. GRANT ALL ON bonus TO passion.

UPDATE : allows the grantee to modify the records in the tables with the UPDATE command. DELETE : allows the grantee to remove from the table with the DELETE command. INSERT : allows the grantee to add records to the table with the INSERT command. WITH : The WITH GRANT OPTION allows the GRANT OPTION grantee to in-turn grant object privileges to other users. : . SELECT : allows the grantee to query the table with the SELECT statement.Object Privileges        ALTER allows the grantee to change the table definition with the ALTER TABLE command. INDEX : allows the grantee to create an index on the table with the CREATE INDEX command.

 REVOKE Statement :    Privileges once given can be denied using the REVOKE command. A user of an object who is not the owner. Syntax : REVOKE { ALL | object privileges } ON object_name FROM user_ name. has the power to REVOKE the privileges from grantee.  REVOKE UPDATE ON bonus FROM passion. E. but has been granted the GRANT privilege. The object owner can revoke privileges granted to another user. .g REVOKE ALL ON bonus FROM passion.

END12 .

PL / SQL .

A block of PL/SQL code contains three sections :  Declarations :   Defines and initializes the variables and cursors used in block. .Introduction    PL/SQL if Oracle‟s Procedural Language (PL) superset of Structure Query Language (SQL). Executable Commands : Uses flow-control commands (such as if commands and loops) to execute the commands and assign values to the declared variables. The Executable commands section is followed by Exception Handling Section. The exception keyword signals start of the block.    The Declarations section starts with the keyword declare and ends when the Executable commands section starts (as indicated by the keyword begin). Exception Handling : Provides customized handling of error handling. The PL/SQL block is terminated by the end keyword. PL/SQL code is grouped into structures called blocks.

 The structure of a typical PL/SQL block is as follows : declare <declarations section> begin <executable commands> exception <exception handling> end. .

and facilities displaying user-friendly messages. . all sorts of calculations can be done quickly and efficiently without the use of the Oracle Engine. branching and looping. Via PL/SQL. PL/SQL sends an entire block of statements to the Oracle engine at one time. The communication between the program block and the Oracle engine reduces considerably. PL/SQL allows declaration and use of variables in blocks of code. PL/SQL also permits dealing with errors as required.Advantages of PL/SQL       Pl/SQL is development tool that not only supports SQL data manipulation but also provides facilities of conditional checking. where Oracle is operational. Applications written in PL/SQL are portable to any computer hardware and operating system. This in turn reduces network traffic. This considerable improves transaction performance. Hence PL/SQL code blocks written for a DOS version of Oracle will run on it‟s UNIX version without any modifications at all. when errors are encountered.

* / < > = ! . : . “ # $ ^ & _ \ { } ? [ ]  Words used in a PL/SQL block are called Lexical Units. The Ordinary Symbols used in PL/SQL blocks are :    ()+-*/<>=. Blank spaces can be freely insert between lexical units in a PL/SQL block. „ @ % .PL/SQL Character Set   THE CHARACTER SET : The Basic character set includes the following :     Uppercase alphabets { A – Z} Lowercase alphabets { a – z} Numerals ( 0 – 9) Symbols : ( ) + . The spaces have no effect on the PL/SQL block. || << >> The Compound Symbols used in PL/SQL blocks are :  ..%„“ < > != ~= ^= <= >= := ** .

„B‟. Example : „&‟. 8g3. 56e-04. The values it can take are :TRUE. You can represent the single quote character itself.e5.. „Passion‟‟s POP makes the difference. This will not be the same as a double quote.  String Literal :    Character Literal :    Logical (Boolean) Literal :  . . 1. in a string literal by writing it twice.89. 1. If a float is being represented.   LITERALS : A literal is a numeric value or a character string used to represent itself. NULL. +67. Numeric Literal :   These can be either integers or floats. Example : 56.‟ These are string literals consisting of single characters. then the integer part must be separated from the float part by a period. „A‟ These are predetermined constants. FALSE.-90 These are represented by one or more legal characters and must be enclosed within single quotes. Example : „Passion Infotech‟.1. 7.

PL/SQL can use %TYPE attribute to declare variables based on definitions of column in a table.PL/SQL Data Types     The default data types that can be declared in PL/SQL are Number (for storing numeric value). FALSE. Char. Boolean (for storing TRUE. %TYPE declares a variable or constant to have the same datatype as that of a previously defined variable or of a column in a table or in a view. and allows programs to adapt to changes made to the table. Number. if a column‟s attribute change. Date (for storing date and time data). Date data types can have NULL values. Hence. the variable‟s attribute will change as well. This provides for data independence. NOT NULL causes creation of a variable or a constant that cannot have a null value. NULL). Char (for storing character data). . reduces maintenance costs.

PL/SQL supports the comparison between variables and constants in SQL and PL/SQL statements. Variables :    Variables in PL/SQL blocks are named variables. Declaring a constant is similar to declaring a variable except that you have to add the keyword „constant‟ and immediately assign a value to it. Thereafter.  Constants :   Logical Comparison :  . Variable must be separated from each other by at least one space or by a punctuation mark. A variable name must begin with a character and can be followed by a maximum of 29 characters. while the constant is within the scope of the PL/SQL block. colon followed by an equal to sign)  Selecting or fetching table data values into variables.e. no further assignments to the constants are possible. Assigning values to Variables : The assignment of a value to a variable can be done in two ways :  Using the assignment operator := (i. Reserved words cannot be used as variable names unless enclosed within double quotes.

put_line(„Message‟). These functions can be used to display message to the user. Syntax :   SET SERVEROUTPUT ON. . DBMS_OUTPUT : It is a package that includes a number of procedures and functions that accumulate information in a buffer so that it can be retrieve later. Put_line expects a single parameter of character data type. Displaying user Message on Screen :  Syntax : dbms_output.    To display message to the user the SERVEROUTPUT should be set ON. SERVEROUTPUT is a SQL *PLUS environment parameter that displays the information passed as a parameter to the PUT_LINE function. PUT_LINE : Put a piece of information in the package buffer followed by an endof-file marker.

This technique can also be used to enclose a section of a PL/SQL block that temporarily needs to be isolated and ignored. . This form of specifying comments can be used to span across multiple lines. The entire line will be treated as a comment.  The comment line begins with a slash followed by an asterisk (/*) till the occurrence of an asterisk followed by a slash (*/). All lines within are treated as comments. Comments : A comment can have two forms :  The comment line begins with a double hyphen (--).

 A sample program of PL/SQL : declare a number (3).  . SQL> / Program will show the output like : A = 10 PL/SQL procedure successfully completed. begin a := 10. end. dbms_output. How to run a program ? SQL> set serveroutput on.put_line(„A =„ ||a).

In PL/SQL.Conditional Control in PL/SQL  PL/SQL allows the use of IF statement to control the execution of a block of code. Syntax : IF <condition> THEN < Action > ELSEIF <condition> THEN < Action > ELSE < Action > END IF.  . the IF-THEN – ELSE-ELSE-END IF construct in code blocks allow specifying certain conditions under which a specific block of code should be executed.

If acc_balance >= min_bal then update accounts set acc_bal = acc_bal . end if.debit_amt Where acc_id=acc_no. debit_amt number(5):=2000. else dbms_output. acc_balance:=acc_balance . min_bal constant number(5.2):=500.g:- Declare /*Declaration of memory variables & constants to be used in the Execution section */ acc_balance number(8).E. Select acc_bal into acc_balance from accounts where acc_id = acc_no. acc_no varchar2(6).put_line(“Insufficient Balance”). End. Begin /* Accept an account_no from the user */ acc_no:=&acc_no. .debit_amt.

A loop marks a sequence of statements that has to be repeated. while the keyword end loop is placed immediately after the last statement.Iterative Control  Iterative control indicates the ability to repeat or skip sections of a code block. PL/SQL supports following structures for iterative control : The WHILE Loop : WHILE <condition> LOOP < Action > END LOOP. The keyword loop has to be placed before the first statement in the sequence of statements to be repeated.   .

2).2):=3. radius number(5).Set serveroutput on Declare pi constant number(4. End loop. area number(14. insert into square values(radius. End. radius:=radius+1. While radius <=7 Loop area:=pi * power(radius. .area). begin radius:=3.2).14.

insert into square values(a. begin a:=&a. . End loop.sq). While a <=7 Loop sq:=a * a. a:=a+1. End.Set serveroutput on Declare a square. sq number(2).num%type.

 The variable in the FOR Loop need to be declared. Also the increment value cannot be specified. . The FOR Loop : FOR variable IN [REVERSE] start . The For Loop variable is always be increment by 1. end LOOP < Action > END LOOP..

dbms_output.declare a number(3).put_line(' b='||b). for a in Reverse 1. . Begin a:=1. b number(3). End loop.. End. b:=&b.5 loop b:= b+1.

salary. (totbasic will now be of the same type as basic column from the table.%Type and %Rowtype  %Type : It is used in PL/SQL to declarare a variable to be of the same type as a previously declared variable or to be of the same type as a column in table.Variable Attribute .) . Example: Declare TOTBASIC SALARY.BASIC%TYPE.

) . Example: SALREC SALARY%ROWTYPE. (salrec is a record variable equivalent to the row from the table. %Rowtype: It is declare a variable which is actually a record which is the same structure as a row from a table. salary.

END13 .

Rollback.Oracle Transactions    A series of one or more SQL statements that are logically related. table data can be changed or all changes made to the table data undone.  Using COMMIT :  . Committing changes to the database. By using these statements.  Closing Transactions :  A transaction can be closed by using either a commit or rollback statement. rollback or connection made to the Oracle engine.   Disconnecting from Oracle. A COMMIT ends the current transaction and makes permanent any changes made during the transaction. A transaction begins with the first executable SQL statement after a commit. Specifically. a transaction is a group of events that occurs between any of the following events :   Connecting to Oracle. or a series of operations performed on Oracle table data is termed as a Transaction.

Syntax : COMMIT; Using ROLLBACK :

A ROLLBACK does exactly opposite of COMMIT. It ends the transaction but undoes any changes made during the transaction. All transaction locks acquired on tables are released. Syntax : ROLLBACK [WORK] [TO [SAVEPOINT] savepoint ]; Where : WORK : is optional and is provided for ANSI compatibility. SAVEPOINT : is optional and is used to rollback a partial transaction, as far as the specified savepoint. savepoint : is a savepoint created during the current transaction.

Creating SAVEPOINT :

SAVEPOINT marks and saves the current point in the processing of a transaction. When a SAVEPOINT is used with a ROLLBACK statement, parts of a transaction can be undone. An active savepoint is on that is specified since the last COMMIT or ROLLBACK.

Syntax : SAVEPOINT savepointname; ROLLBACK can be fired from the SQL prompt with or without the SAVEPOINT clause. A ROLLBACK operation performed without the SAVEPOINT :
   

Ends the transaction. Undoes all the changes in the current transaction. Erases all savepoints in that transaction. Releases the transaction locks.

A ROLLBACK operation performed with the SAVEPOINT :
  

A predetermined portion of the transaction is rolled back. Retains the save point rolled back to, but loses those created after the named savepoint. Releases all transactional locks that were acquired since the savepoint was taken.

Declare totsal number(9); Begin insert into worker values('E007','Mock',1000); savepoint no_update; update worker set sal= sal+2000 where name = 'Blake'; update worker set sal = sal + 1500 where name = 'Clark'; select sum(sal) into totsal from worker; if totsal>50000 then rollback to savepoint no_update; end if; commit; end;

END14 .

  The Oracle Engine uses a work area for its internal processing in order to execute an SQL statement. Such user-defined cursors are known as „Explicit Cursors. This work area is private to SQL‟s operations and is called Cursor. Conceptually. The data that is stored in the cursor is called the Active Data Set. the size of the cursor in memory is the size required to hold the number of rows in the Active Data Set. Hence the cursor‟s size will be limited by the size of this pre-defined area. TYPES OF CURSORS : Cursors are classified depending on the circumstances under which they are opened. is determined by the Oracle‟s engine‟s built in memory management capabilities and the amount of RAM available. within cursors are opened. A user can also open a cursor for processing data as required. If the Oracle engine for its internal processing has opened a cursor they are known as „Implicit Cursors‟. CURSORS   . The actual size however. Oracle has a pre-defined area in main memory set aside.

FALSE otherwise. %ISOPEN %FOUND %NOTFOUND %ROWCOUNT . FALSE otherwise. the Oracle engine creates a set of four system variables which keeps track of the „Current‟ status of the cursor. These cursor variables can be accessed and used in a PL/SQL code block. Returns number of records processed from the cursor.General Cursor Attributes  When the Oracle Engine creates an implicit or explicit cursor control variables are also created to control the execution of the cursor. Both Implicit and Explicit cursors have four attributes. Returns TRUE if record was not fetched successfully. They are described below : Attribute Name Description Returns TRUE if cursor is open. FALSE otherwise. Whenever any cursor is opened and used. Returns TRUE if record was fetched successfully.

This can be done by preceding the cursor attribute with cursor name (i. Since the cursor is opened and managed by the Oracle internally. populating this area with appropriate data. releasing the memory area when the processing is complete is taken care of by the Oracle Engine. delete or single-row select statements. Implicit cursor attributes can be used to access information about the status of last insert. Implicit Cursor :  The Oracle Engine implicitly opens a cursor on the Server to process each SQL statement.e. processing the data in the memory area. SQL)  . the function of reserving an area in memory. update.

Attribute Name %ISOPEN %FOUND %NOTFOUND %ROWCOUNT . or a single-row select returned one or more rows. or a single-row select returns no rows. The syntax for accessing this attribute is SQL%NOTFOUND. Otherwise it evaluates to FALSE. update or delete SQL statement has been processed in case of implicit cursors. Is the logical opposite to %FOUND. update or delete affected no rows. The syntax for accessing this attribute is SQL%ROWCOUNT. if an insert. Returns number of rows affected by an insert. insert. Otherwise. Implicit Cursor Attributes : Description The Oracle engine automatically opens and closes the SQL cursor after executing its associated select. Evaluates to TRUE. As a result. Thus the SQL%ISOPEN attribute of an implicit cursor cannot be referenced outside of its SQL statement. if an insert. update or delete or select into statement. it evaluates to FALSE. update or delete affected one or more rows. Syntax is SQL%FOUND. It evaluates to TRUE. SQL%ISOPEN always evaluated to FALSE.

put_line('Employee Record Modified Successfully').Example for SQL%Found: Begin update emp set sal = sal *0. end.put_line('Employee no. Does not exist').15 Where empno=&empno. else dbms_output. end if.  . If SQL%found then dbms_output.

 Example for SQL%NOTFound: Begin update emp set sal = sal +(sal *0. end if. .put_line('Employee Record Modified Successfully'). If SQL%NOTfound then dbms_output. else dbms_output.15) Where empno=&empno.put_line('Employee no. Does not exist'). end.

rows_affected:= to_char(sql%rowcount). else dbms_output. Begin update emp set sal = sal * 500 Where ename = &ename. End. Example for SQL%ROWCOUNT: Declare rows_affected char(4). End if.put_line(rows_affected || 'Employee Record Modified Successfully'). .put_line('There are no Employees name as scott'). if sql%rowcount > 0 then dbms_output.

Initialization of a cursor takes place via the open statement. creates Active Data Set. It is declared in the Declare section of the PL/SQL block and used with Executable section. Explicit Cursors :   Cursor declared by the user is called Explicit Cursor. Fetch and Close commands :  Defines a private SQL area named after the cursor name. Sets the cursor row pointer in the Active Data Set to the first record. . This is done by naming the cursor and mapping it to a query.e.  A fetch statement then moves the data held in the Active Data set into memory variables. Executes a query associated with the cursor which retrieves table data and populates the named private SQL area in memory i. this     Cursor Declaration :   The functionality of Open. A cursor is defined in the declarative part of PL/SQL block.

The fetch statement is placed inside the Loop … End Loop construct, which causes the data to be fetched into the memory variables and processed until all the rows in the Active Data Set are processed. After the fetch loop exits, the cursor must be closed with the close statement. This will release the memory occupied by the cursor and its Active Data Set. CURSOR cursor_name IS SQL Select statement ; OPEN cursor_name ;

Syntax for Declaration of a Cursor :

 

Syntax for Opening a Cursor :

Syntax for Fetching a record from the cursor :

FETCH cursor_name INTO variable1, variable2…… ;
CLOSE cursor_name ;

Syntax for Closing a Cursor :

Explicit Cursor Attributes :
Description Evaluates to TRUE, if an explicit cursor is open; or to FALSE if it is closed. The Syntax for accessing this attribute is cursor_name %ISOPEN.

Attribute Name %ISOPEN


Evaluates to TRUE, if last fetch succeeded because a row was available; or to FALSE if the last fetch failed because no more rows were available. The Syntax for accessing this attribute is cursor_name%FOUND.
Is the logical opposite to %FOUND. It evaluates to TRUE, if the last fetch has failed because no more rows were available, or to FALSE, if the last fetch returned a row. The syntax for accessing this attribute is cursor_name%NOTFOUND. Returns number of rows fetched from the active data set. It is set to zero when the cursor is opened. The syntax for accessing this attribute is cursor_name%ROWCOUNT.




Declare cursor c_emp is select empno, sal from emp where deptno =&deptno; str_emp_code emp.empno%type; num_salary emp.sal%type; Begin Open c_emp; If c_emp%isopen then loop fetch c_emp into str_emp_code, num_salary; exit when c_emp%notfound; update emp set sal = num_salary + (num_salary * .05) Where empno = str_emp_code; insert into emp_raise values(str_emp_code, sysdate, num_salary * 0.05); end loop; Commit; Close c_emp; Else dbms_output.put_line('Unable to open cursor'); end if; end;

loop fetch c_emp into str_emp_code. EXAMPLE FOR CURSORNAME%FOUND: Declare cursor c_emp is select empno.05). else exit. num_salary.sal%type. sysdate. Begin Open c_emp.05) Where empno = str_emp_code. End if. num_salary*0. Commit. str_emp_code emp. num_salary emp. Close c_emp. .empno%type. sal from emp where deptno =20. End loop. If c_emp %found then update emp set sal = num_salary + (num_salary * . End. insert into emp_raise values(str_emp_code.

num_deptno emp. end.deptno.put_line('----------------------').deptno%type. close c_emp. dbms_output. '||num_salary).sal%type.ename%type. Begin Open c_emp.put_line('Name Department Salary').sal from emp where deptno=&deptno. str_ename emp. dbms_output. num_salary emp. exit when c_emp%rowcount = 10 or c_emp%notfound. num_deptno. EXAMPLE FOR CURSORNAME%ROWCOUNT: Declare cursor c_emp Is select ename. loop fetch c_emp into str_ename. num_salary. .put_line(str_ename||' '||num_deptno||' end loop. dbms_output.

END15 .

. This privilege is part of the resource role. Update) is performed on a table for which the trigger has been written. the user must have the Create trigger privilege. which defines some action that the database should take when some database – related event occurs. Triggers are executed when a data manipulation command (Insert. Triggers are executed automatically and are transparent to the user. In order to create a trigger.TRIGGERS     A Trigger consists of PL/SQL code. Delete.

UPDATE. 2. Trigger Event :DELETE . Derive column values. OR INSERT issued against the table. 3. To enforce certain business rules (validation) in an application. 1. USE: TO enforce rules that cannot be coded through refertial integrity.  .

constant declarations. Begin PL/SQL subprogram body. . Tablename [Referencing {OLD AS old.Syntax: Create [or replace] trigger <trigger name> [before | after] [delete | insert | update] [of column] On [user]. NEW AS new }] [FOR EACH ROW [WHEN condition] ] Declare variable declarations. END.

name varchar2(20). Insert into auditclient values(client_no. If deleting then oper:='delete' end if.user. name:=:old. Example: CREATE TRIGGER dudu after update or delete on client_master FOR each row Declare oper varchar2(8). end if. .client_no.oper.sysdate).name. end. client_no:=:old. Begin If updating then oper:='update'. city varchar2(10). client_no varchar2(6).

 . E.g:DROP TRIGGER dudu.Deleting a Trigger:  Syntax: DROP TRIGGER triggername.

.Functions: Functions are also a collection of SQL and PL/SQL code which can return a value to the caller.

 E.g:Create or replace function sqno(no number) return number Is Begin return no*no.put_line('10 square is '||sqno(10)). /  . end. end. set serveroutput on Begin dbms_output.

g:Create or replace function netsal(ID IN emp. Return(netsal).E.sal%type. Begin Select sum(sal) into netsal from emp where empno=id. .empno%type) Return number IS netsal emp. End.

END16 .

The description of database is held in the same way as ordinary data and is accessible to authorized users.   Rule 1 : The Information Rule :  All information is explicitly and logically represented in tables as values. view definition. Each and every data is logically accessible through a combination of table name. column name and primary key value. authorization and transactional control. There must be one language which is comprehensive in supporting data definition. it must be able to manage the database through its relational capabilities.CODD’s Rules  Rule 0 :  For any system to be called an RDBMS. Inapplicable or missing information can be represented through null values. Rule 2 : The rule of Guaranteed Access :    Rule 3 : The Systematic Treatment of Null values :  Rule 4 : The Database Description Rule (Data Dictionary) :   Rule 5 : Comprehensive Data Sub Language :  . data manipulation. integrity constraint.

table emp is split into emp1 & emp2 & view is created as emp based on emp1. Application program is not affected by this change). All integrity constraints should be stored in the system catalog or in a database as a table. Rule 7 : The Insert & Update Rule :   Rule 8 : The Physical Independence Rule :   Rule 9 : The Logical Data Independence Rule :   Rule 10 : The Integrity Independence Rule :  .g.g. (e. emp2. Application programs remain logically unimpaired whenever any changes are made in the storage representation.CODD’s Rules   Rule 6 : The View Updating Rule :  All views that are theoretically updatable are updated by the system. If index is dropped). Application program and terminal activity remain logically unimpaired when changes of any kind that are made to the base tables (e. All the data manipulation commands must be operational on sets of rows having a relation rather than a single row.

 Rule 12 : The Non-Subversion Rule :  If an RDBMS supports a lower level language then it should not bypass any integrity constraints defined in the higher level.CODD’s Rules  Rule 11 : The Distribution Rule :  The system must be able to access or manipulate the data that is distributed in other systems. .

Sign up to vote on this title
UsefulNot useful