ORACLE

WHAT IS ORACLE ?

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.

TOOLS OF ORACLE

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. Forms : This is a graphical tool used for generating and executing forms based applications. Reports : It is an application development tool of oracle for developing displaying and printing reports. .

STRUCTURED QUERY LANGUAGE .

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

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

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

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

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

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

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

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

 More than one column can be used to query result.  .  ORDER BY clause should be the last clause in SELECT statement.  ASC and DESC.  When data is sorted in the ascending order NULL values appears at the end in sorted column.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.

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

END1 .

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. .ORACLE DATA TYPES Data Type Char (size) Description Represents fixed length characters up to the width size. Number (p. Represents date and time in table in fixed length in 7 bytes. The maximum width is 2000 characters. Default format is „dd-mm-yyy‟. The default width is 1 and maximum width is 255 characters. Varchar2 (size) Represents fixed length characters up to the width size. Number Represents the floating point number with 38 significant digits precision.

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

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

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

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

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

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

End2 .

 .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. The objects name and type are displayed. 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>.

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

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

END3 .

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

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

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) .

profit_percent FROM product_master WHERE profit_percent >=10 AND profit_percent <=20.SELECT product_no.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.g. description. e. .

. e. city. address2.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. name. address1.SELECT clinet_no. pincode FROM client_master WHERE (pincode =400054 OR pincode = 400057.

- . city. address2. name. address1. pincode FROM client_master WHERE NOT (city = „Bombay‟ or city = „Delhi‟). e.g. SELECT clinet_no. 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.

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

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

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

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

In case a value needs to be compared to a list of values then the IN predicate is used. This will select all the rows where values do not match all of the values in the list. 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. The NOT IN predicate is the opposite of the IN predicate. .

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

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

Output : SYSDATE -------------18-FEB-82 . 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. 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 .

ORACLE FUCTIONS .

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

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

END5 .

the function returns -1. If n<0. m) MOD (m. Returns m raised to the nth power.NUMBER FUNCTIONS Function ABS (n) Description Returns the absolute value of n. Returns e raised to the nth power. 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. if n=0 the function returns 0. Returns n truncated to m decimal places if m is omitted to 0 places. m) POWER (m. Returns the remainder of m divided of m divided by n. if n>0 the function returns 1. if m is omitted then n is rounded to 0. . n) TRUNC (n. CEIL (n) ROUND (n. Returns the square root of n.

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

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

SELECT NEXT_DAY(„04-FEB-98‟. .Date Functions SYSDATE ADD_MONTHS LAST_DAY MONTHS_BETWEEN NEXT_DAY Syntax SELECT SYSDATE FROM DUAL.‟FRIDAY‟) “NEXT DAY” FROM DUAL. LAST_DAY(SYSDATE) “LAST” FROM DUAL.4) FROM DUAL. SELECT SYSDATE. SELECT MONTHS_BETWEEN(„02-FEB-92‟.‟02-JAN92‟)”MONTHS” FROM DUAL. SELECT ADD_MONTHS(SYSDATE.

„this‟. this will be replaced by a three-letter abbreviation for the current time zone.TIME FUNCTION NEW_TIME (date. 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. „other‟) : Gives the date (and time) in this time zone.

END6 .

CONVERSION FUNCTIONS
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.

Function
TO_CHAR TO-CHAR TO_DATE ASCII CHR

Syntax
SELECT TO_CHAR(17145,‟$099,999‟) “CHAR” FROM DUAL; SELECT TO_CHAR(HIREDATE, „MONTH DD,YYYY‟) “New Date Format” FROM EMP WHERE EMPNO=11; INSERT INTO EMP (EMPNO,HIREDATE) VALUES „07756‟,TO_DATE („30-SEP-85 10:55 A.M.‟,‟DD-MON-YY HH:MI A.M.‟); SELECT ASCII(„a‟) “ASCII” FROM DUAL; SELECT CHR(97) “CHAR” FROM DUAL;

GROUP FUNCTIONS
  

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.

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

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. SELECT MAX(bal_due) “Maximum Balance” FROM CLIENT_MASTER SELECT SUM(bal_due) “Total Balance Due” FROM CLIENT_MASTER .

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

 e. .g:SELECT PRODUCT_NO. SUM (QTY_OERDERED) “TOTAL QTY ORDERED” FROM SALES_ORDER_DETAILS GROUP BY PRODUCT_NO  e.g:SELECT PRODUCT_NO. SUM (QTY_OERDERED) “TOTAL QTY ORDERED” FROM SALES_ORDER_DETAILS GROUP BY PRODUCT_NO HAVING PRODUCT_NO = „P00001‟ OR PRODUCT_NO =„P00004‟.

END7 .

constraints super control data being entered in tables for permanent storage. . entire record is rejected and not stored in the table. Once define an integrity constraint for a table all program using that table can benefit from it. Thus. 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.CONSTRAINTS        Rules which are enforced on data being entered. Even if single column of the record being entered into the table fails a constraint. Are easy to specify and maintain. When business rule change constraint can be modified centrally. Always conforms to the rule specified by the integrity constraints. Helps to enforce business rules on data. Advantages of Integrity Constraints :     Do not have to program applications to check for the validity of data.

 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.Types of Integrity Constraints  Entity Integrity Constraints :  Ensure that each row in a table is unique.

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

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

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

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

The NOT NULL attribute is active.  A single column primary key is called Simple key.……).   . the column cannot be left blank. Create Table <table name> (column_name data_type (size) PRIMARY 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. The data held across the column must be UNIQUE.e. 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. Create Table <table name> (column_name data_type (size) …… PRIMARY KEY (column_name.…………). column_name.

………) . 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. Create Table <table name> (column_name data_type (size). by default. Oracle references the primary key.Referential Integrity Constraints  FOREIGN KEY constraint :      Foreign key represents relationship between tables. 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. .…) REFERENCES table_name (column. Create Table <table name> (column_name data_type (size) REFERENCES table_name (column. The table in which the foreign key is defined is called a Foreign Table or Detail Table. The master table can be referenced in the foreign key definition by using the REFERENCES adverb.…… FOREIGN KEY (column. If the name of column is not specified.……). column.

END8 .

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

 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 sales_order_details Drop Constraint fk_prno. e.g:ALTER TABLE supplier_master Drop Primary Key. DROP : ALTER TABLE <tablename> DROP <constraint_definition> e. .

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

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.  .g:CREATE TABLE client_master (client_no varchar2(6) CONSTRAINT p_clientkey PRIMARY KEY. address1 varchar2(15).  The syntax is : CONSTRAINT<constraintname> <constraintdefinition> e. name varchar2(25). pincode number(8). bal_due number(10. address2 varchar2(15). city varchar2(10).2)).

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

END9 .

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

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

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

 The subquery result is then compared to the value of the column (s) in the parent statement.Single Row Subqueries Single row subqueries returns a single value from a table.  . 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).  E.g.

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

sal FROM emp WHERE (sal. 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. Solution : SELECT ename. job FROM emp GROUP BY job). job) IN (SELECT max (sal).g. The subquery result is then compared to the value of the column (s) in the parent statement. E. .

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‟). . Solution : SELECT job.

Subqueries are executed from the innermost to the outermost subqueries except in the case of correlated subqueries. 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.Subqueries  A Subquery is a SELECT statement that has a result which is utilized by another SQL statement.

Continue step 1 to 3 until no row from the outer query remains. Behaviour of a correlated subqueryis evaluated as follows:     Get a row from outer query. Sol : select ename. Execute the inner query using the rows value. Use the value resulting from the inner query to qualify or disqualify the row fetched from the outer query.job). job.g. sal from emp e where sal < (select avg (sal) from emp where job = e.   E. . 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.

. 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 .

QUERYING MULTIPLE TABLES .

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

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

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

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

END11 .

DATABASE OBJECTS .

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

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

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

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

INCREMENT BY :

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.

 

MINVALUE :

NOMINVALUE :

 

MAXVALUE :

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.

NOMAXVALUE :

START WITH

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.

CYCLE :

NOCYCLE :

CACHE :

If the ORDER / NOORDER clause is omitted.  ORDER :  This guarantees that sequence numbers are generated in the order of request. This is only necessary if you are using Parallel Server in Parallel mode option. In exclusive 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. a sequence always generates numbers in order. This is only necessary if you are using Parallel server in Parallel mode option. a sequence takes the NOORDR clause by default.

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

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

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

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

DELETE : allows the grantee to remove from the table with the DELETE command.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. INSERT : allows the grantee to add records to the table with the INSERT command. UPDATE : allows the grantee to modify the records in the tables with the UPDATE 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.

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

END12 .

PL / SQL .

Exception Handling : Provides customized handling of error handling. The PL/SQL block is terminated by the end keyword.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 Declarations section starts with the keyword declare and ends when the Executable commands section starts (as indicated by the keyword begin). The Executable commands section is followed by Exception Handling Section. A block of PL/SQL code contains three sections :  Declarations :   Defines and initializes the variables and cursors used in block. PL/SQL code is grouped into structures called blocks. . The exception keyword signals start of the block.

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

PL/SQL sends an entire block of statements to the Oracle engine at one time. Via PL/SQL. 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. and facilities displaying user-friendly messages. Hence PL/SQL code blocks written for a DOS version of Oracle will run on it‟s UNIX version without any modifications at all. Applications written in PL/SQL are portable to any computer hardware and operating system. where Oracle is operational. PL/SQL allows declaration and use of variables in blocks of code. when errors are encountered. branching and looping. The communication between the program block and the Oracle engine reduces considerably. . This considerable improves transaction performance. This in turn reduces network traffic. all sorts of calculations can be done quickly and efficiently without the use of the Oracle Engine.

The spaces have no effect on the PL/SQL block.%„“ < > != ~= ^= <= >= := ** .* / < > = ! . : . “ # $ ^ & _ \ { } ? [ ]  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. || << >> The Compound Symbols used in PL/SQL blocks are :  ..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 : ( ) + .

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

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

 Variables :    Variables in PL/SQL blocks are named variables.e. no further assignments to the constants are possible. PL/SQL supports the comparison between variables and constants in SQL and PL/SQL statements. 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. colon followed by an equal to sign)  Selecting or fetching table data values into variables. while the constant is within the scope of the PL/SQL block. Thereafter. A variable name must begin with a character and can be followed by a maximum of 29 characters. Variable must be separated from each other by at least one space or by a punctuation mark.  Constants :   Logical Comparison :  . 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.

These functions can be used to display message to the user. 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(„Message‟). Displaying user Message on Screen :  Syntax : dbms_output. Put_line expects a single parameter of character data type.    To display message to the user the SERVEROUTPUT should be set ON. PUT_LINE : Put a piece of information in the package buffer followed by an endof-file marker. Syntax :   SET SERVEROUTPUT ON. SERVEROUTPUT is a SQL *PLUS environment parameter that displays the information passed as a parameter to the PUT_LINE function. .

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

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

Conditional Control in PL/SQL  PL/SQL allows the use of IF statement to control the execution of a block of code. In PL/SQL. 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.  .

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

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

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

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

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

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

%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. salary. Example: Declare TOTBASIC SALARY. (totbasic will now be of the same type as basic column from the table.BASIC%TYPE.) .Variable Attribute .

Example: SALREC SALARY%ROWTYPE.) . salary. (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.

END13 .

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

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 .

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

FALSE otherwise.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. Returns TRUE if record was fetched successfully. These cursor variables can be accessed and used in a PL/SQL code block. Returns number of records processed from the cursor. Whenever any cursor is opened and used. %ISOPEN %FOUND %NOTFOUND %ROWCOUNT . Both Implicit and Explicit cursors have four attributes. FALSE otherwise. FALSE otherwise. the Oracle engine creates a set of four system variables which keeps track of the „Current‟ status of the cursor. They are described below : Attribute Name Description Returns TRUE if cursor is open. Returns TRUE if record was not fetched successfully.

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

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

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

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

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

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

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

%FOUND

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.

%NOTFOUND

%ROWCOUNT

EXAMPLE FOR CURSORNAME%ISOPEN:

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;

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

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

END15 .

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

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

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

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

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

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

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

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

END16 .

  Rule 1 : The Information Rule :  All information is explicitly and logically represented in tables as values. The description of database is held in the same way as ordinary data and is accessible to authorized users. Inapplicable or missing information can be represented through null values. Each and every data is logically accessible through a combination of table name. integrity constraint. 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 :  . There must be one language which is comprehensive in supporting data definition. view definition. authorization and transactional control. it must be able to manage the database through its relational capabilities. column name and primary key value. data manipulation.CODD’s Rules  Rule 0 :  For any system to be called an RDBMS.

g. 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. Application programs remain logically unimpaired whenever any changes are made in the storage representation. emp2. 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 :  .CODD’s Rules   Rule 6 : The View Updating Rule :  All views that are theoretically updatable are updated by the system. All integrity constraints should be stored in the system catalog or in a database as a table. (e. table emp is split into emp1 & emp2 & view is created as emp based on emp1.g. Application program is not affected by this change). If index is dropped).

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.  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. .

Sign up to vote on this title
UsefulNot useful