9i

SL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Contents
Introduction To DBMS Oracle Data Type Structure Query Language (SQL) Sql* Plus Editing Commands Sql * Plus File Commands Data Retrieval/Query Language (Drl/Dql) (Select) Data Manipulation Language (DML) (Insert, Update, Delete, Merge) Data Dictionary Language (DDL) (Create, Alter, Drop, Truncate, Rename) Data Control Language (DCL) (Grant, Revoke) Transaction Control Language (TCL) (Commit, Rollback, Savepint) Oracle Functions Group By Clause Integrity Constraints Joins Sub Queries Working With Database Objects • Views • Sequences • Inedexes • Synonyms • Cluster Partitions Locking Mechanism More Commands In Oracle 9i Pl/Sql Cursor Exception Handling Procedures Functions PACKAGE And PACKAGE BODY Trigger File Input/Output (I/O) (Utl_File) Oracle Supplied Packages New SQL Function In Oracle 9i Implementing Object Techniques Using Lobs Some Advance Fetures In Oracle 9i Oracle Utilities • Export • Import • Sql Loader Oracle Architecture

Page No

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

34

Introduction to DBMS Database: A Database is a collection of inter-related data from which some information can be extract. Database Management System (DBMS) Database Management Systems organize and structure data so that it can be retrieved and manipulating by users and application programmer. Database Model: The data structures and access techniques provided by a particular DBMS are called as Data Model. • Hierarchical • Network • Relational Hierarchical data model: - This model is like a hierarchical tree structure; used to construct a hierarchy of records in the form of nodes and branches. The data elements presnt in the structure of parent/ child relationship. - Every child has one parent. - You can see only one record at a time. - Retrieving the data in a Hierarchical database thus required navigating through the records, Moving up, down, sideways one record at a time. - Example Windows Explorer - Developed By IBM Named as Information Management System (IMS) in 1968 The Drawback of Hierarchical data model - It cannot handle a large data - It’s not support many to many to relation Network data model - The simple structure of a Hierarchical database became a disadvantage when the data had a more complex structure. In an order-processing database, for example, a single order might participate in three different parent/child relationships, linking the order to the customer who placed it, the salesperson who took it, and the product ordered. The Network model extended the Hierarchical model by allowing a record to participate in multiple parent/child relationship Network databases had their disadvantages like Hierarchical database, they where very rigid. The set relationships and the structure of the records had to be specified in advance. The Drawback of Network data model - Changing the database structure typically required rebuilding the entire database. Relational Model • • • • Data is organized in terms of rows and columns in a table knowns as relations The position of a row in a table is of no importance. The intersection of row and column must give a single value and not a set of values. Column name must be unique

2

• • •

Row must be unique It eliminated the explicit parent/child structures from the database, and instead of represented all data in the database as simple row/column tables of data values. A relational database is a database where all data visible to the user is organized strictly as tables of data values, and where all database operations work on these tables.

The publication of the paper “A relational Model of Data for Large Shared Database” by Dr. E.F. Codd in June 1970 in the “Communication of ACM” , set a trend for virgorous and extensive investigation into a theoretical frame work to support further work in the area of Data Modelling. The end result is the Relational Database Management System.

The 12 Rules for an RDBMS (Codd' s Rule)
Rule 1: The information Rule All Information is explicitly and logically represented in exactly one way i.e by data values in tables. Rule 2: The rule of guaranteed access Every item of data must be logically addressable by resorting to a combination of a Table name, Primary key and column name. Rule 3: The systematic treatment of null value This rule states that support for null values must be consistent throughout the DBMS, and independent of the data type of the field. Rule 4: The Database Description Rule A description of the database is held and maintained using the same logical structures used to define the data. This allows users to query such information in the same way and using the same language, as they would do for any other data in the database. Rule 5: Comprehensive sub-language Rule There must be at least one language whose statements can be expressed as character strings confirming to some well-defined syntax, which is comprehensive in supporting the following: - Data definition, view Definition, Data Manipulation - Integrity Constraints - Authorization - Transaction Boundaries All the above topics are manageable through Structural Query Language (SQL) statement. Rule 6: The view-updating Rule All views that are theoretically updateable are also updated by the system. A view is a table is non-existent in its own right, but instead derived from one or more base tables. Rule 7: The High Level Insert, Update and Delete Rule The capability to handling a base relation, or infact a derived relation, as a single operand must hold good for all retrieve, update, delete and insert activity. This means that the major DML commands, namely SELECT, UPDATE, DELETE and INSERT must be available and operational on sets of rows in a relation. Rule 8: The physical independence Rule The user access to the database remains logically consistent even if the storage representation is changed.

3

one HOD 4 .| | ----\/ ------Many to one _____ _______ | | | | | | -->>--. row-at-a-time processing. Rule 12: Non-Subversion Rule If an RDBMS supports a lower level language that permits for example.| | ----\/ ------One to many _____ _______ | | | | | | -->--. An RDBMS product has to satisfy at least six of the 12 rules of Codd to be accepted as full fledged RDBMS. set-at-a-time./\ --<---. Entity Relationship Diagram ER Diagram: logical database design (through the papers) One to One _____ _______ | | | | | | -->--. relational language. (1:1) ./\ --<---. The following integrity rules should apply every relational database Entity Integrity: No component of a primary key can have missing values or null values. Referential Integrity: For each distinct foreign key value there must exist a matching primary key value in the same domain. Application running on a non-distributed database must remain logically unimpaired if that data becomes distributed in the context of a distributed relational database. then this language must not be able to bypass any integrity rules or constraints defined in the higher level. Rule 10: Integrity independence Rule All integrity constraint defined for a database must be definable in the language and stored in the database as data in tables./\ --<<---.| | ----\/ ------- Degree of Relationship One to one.Rule 9: The logical data independence Rule Application programs and terminal activities must remain logically unimpaired whenever information preserving changes of any kind./\ --<<---.| | ----\/ ------Many to Many _____ _______ | | | | | | -->>--. are made to the base tables. that are theoretically permitted.one department . Rule 11: Distribution Rule A RDBMS must have distribution independence.

The main advantage of using object –orriented concepts to design is that databse is that such a databse is fully compatible with object – oriented applications and systems. Finally Forth Normal Form (4NF). Morever.One HOD . 5 .One to many: (1:M) . Description of Normalization Forms: First Normal Form (1NF) sets the very basic rules for an organized database: . This column is called the primary key.many Teacher Many to one (M:1) . concurrencey control and recovery. .A relation is in BCNF if and only if determinant is a candidate key. It tries to collate the persistence of a DBMS with the expressiveness of an object-oriented programming language. . Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored. Object-Oriented Relational Database Management System (OORDBMS) An Object-Oriented Relational Database Management System (OORDBMS) integrates a DBMS with the concepts of object-oriented programming.Many teachers .oriented databse thus stores persistent objects permanaetly on secondary storage. also known as Boyce. An OORDBMS permits these objects to be shared among different applications by provididng necessary DBMS functions such as indexing. Third Normal Form (3NF) goes one large step further: .Remove subsets of data that apply to multiple rows of a table and place them in separate rows. each table possessing a set of one or more columns. an OORDBMS is oriented towards operations on single objects. Primary key: In a well.Create relationships between these new tables and their predecessors through the use of foreign keys.designed relational database every table has some column or combination of columns whose values uniquely identify each row in the table. Foreign Key: A column in one table whose value matches the primary key in some other table is called as a foreign key. An Object. Relational Database Management System (RDBMS) A Relational Database Management System (RDBMS) is an information system that presents information as rows contained in a collection of tables.Codd normal form (BCNF) has one requirement: .Many students Normalization: It’s a process of efficiently organizing data in a database.HOD Many to Many (M:N) . RDBMSs are very inefficient in their performance with single objects.Eliminate duplicative columns from the same table. There are two goals of Normalization Process: eliminate redundant data (for example. storing the same data in more than one table) and ensure data dependencies make sense (only storing related data in a table).Removes columns that are not dependant upon the primary key.Create separate tables for each group of related data and identity each row with a unique column (Primary Key) Second Normal Form (2NF) further addresses the concept of removing duplicative data: .Many Courses .

documents or arrays of binary data. Maximum size is 2000 bytes or characters.1) * (database block size). (fractional_seconds_p fractional_seconds_precision is the number of digits in the fractional recision) part of the SECOND datetime field.Oracle DATA Type S. with an upper limit of 2000 bytes. Maximum size is 2000 bytes. (fractional_seconds_p where fractional_seconds_precision is the number of digits in the recision) WITH TIME fractional part of the SECOND datetime field. Maximum size is 4000 bytes or characters. Maximum size is determined by the national character set definition. TIMESTAMP All values of TIMESTAMP as well as time zone displacement value. Raw binary data of length size bytes. Both fixed-width and variable-width character sets are supported. sound. Number having precision p and scale s. A binary large object. 4712 BC to December 31.s) INTEGER DATE LONG BLOB CLOB/NCLOB 11 12 RAW (size) LONG RAW 13 BFILE New Data Type in Oracle 9i 14 TIMESTAMP Allow the time to be stored as a data with fraction of seconds. Raw binary data of variable length up to 2 gigabytes. Enables byte stream I/O access to external LOBs residing on the database server. A character large object containing single-byte or multibyte characters. Maximum size is (4 gigabytes . Valid date range from January 1. The scale s can range from -84 to 127. Character data of variable length up to 2 gigabytes. 3 4 VARCHAR2 NVARCHAR2 5 6 7 8 9 10 NUMBER (p. Maximum size is 4 gigabytes. Default and minimum size is 1 character. Maximum size is determined by the national character set definition. You must specify size for a RAW value.1) * (database block size). Stores integer numbers.Stores national character set data. Contains a locator to a large binary file stored outside the database.I 1 2 Data Type CHAR NCHAR Description Fixed-length character data of length size bytes. An Integer number does not contains a floating point. 9999 AD. ZONE 15 6 . Maximum size is (4 gigabytes . with an upper limit of 4000 bytes. The precision p can range from 1 to 38. LONG RAW Can be used to stores graph. Variable-length character string having maximum length size characters. both using the database character set. or 231 -1 bytes. Variable-length character string having maximum length size bytes or characters. Fixed-length character data of length size characters. NCLOB: .

34. SQL> select * from emp23 . SYSDATE+D --------08-NOV-05 timestamp with time zone TIMESTAMP (fractional_s econds_preci sion) WITH LOCAL TIME ZONE INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND 7 .0000000 AM SQL> create table emp23 (empno number(2). SQL> insert into emp23 values (23. order_date timestamp with local time zone) . users see the data in the session time zone.00. where year_precision is (year_precision) TO the number of digits in the YEAR datetime field. SQL> select to_char(sysdate+loan_duration. SQL> select sysdate+day_duarion from emp23 . SQL> insert into emp23 values (23. start_date timestamp with time zone) .16 TIMESTAMP All values of TIMESTAMP WITH TIME ZONE.24. SQL> insert into emp23 values (23.'15-Nov-2004 09:34:24 AM') . The default is 2. SQL> select * from emp23 .000000 AM +05:30 SQL> create table emp23 (empno number(2). SQL> insert into emp23 values (23.'dd-mon-yyyy') from emp23 . start_date timestamp(7)) . SQL> select * from emp23 . INTERVAL DAY Allows time to be stored as an interval of days to hours. INTERVAL YEAR Stores a period of time in years and months. SQL> insert into emp23 values (23.interval '120' month(3)) . minutes (day_precision) TO and second. Stores a single precision 64-bit floating-point number. day_duarion interval day (3) to second) . Useful in presenting the precise difference between two SECOND date time values (fractional_seconds_p recision) 17 18 New Datatypes in 10g 19 20 BINARY_FLOAT BINARY_DOUBLE Stores a single precision 32-bit floating-point number.00.interval '180' day(3)) .'15-nov-04 09:34:34 AM') . TO_CHAR(SYS -----------------12-may-2015 SQL> create table emp23 (empno number(2).'02-may-2005') . Accepted values are MONTH 0 to 9. loan_duration interval year (3) to Month) .34. EMPNO ORDER_DATE --------------------------------------------------------------------------23 15-NOV-04 09. EMPNO START_DATE --------------------------------------------------------------------------23 02-MAY-20 05. with the following (fractional_seconds_p exceptions: recision) WITH LOCAL • Data is normalized to the database time zone when it is TIME ZONE stored in the database.000000 AM SQL> create table emp23 (empno number(2). EMPNO START_DATE --------------------------------------------------------------------------23 15-NOV-04 09.34. Example of The New data Type In Oracle 9i TIMESTAMP SQL> create table emp23 (empno number(2). • When the data is retrieved.

Keyword cannot be abbreviated .SQL is a database access. ALTER. EMPNO 7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934 ENAME SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS suresh FORD MILLER JOB CLERK SALESMAN SALESMAN MANAGER SALESMAN MANAGER MANAGER ANALYST PRESIDENT SALESMAN CLERK DBA ANALYST CLERK MGR HIREDATE 7902 17-DEC-80 7698 20-FEB-81 7698 22-FEB-81 7839 02-APR-81 7698 28-SEP-81 7839 01-MAY-81 7839 09-JUN-81 7566 19-APR-87 17-NOV-81 7698 08-SEP-81 7788 23-MAY-87 7698 03-DEC-81 7566 03-DEC-81 7782 23-JAN-82 SAL 800 1600 300 1250 500 2975 1250 1400 2850 2450 3000 5000 1500 0 1100 9000 4000 1300 COMM DEPTNO 20 30 30 20 30 30 10 20 10 30 20 30 20 10 SQL> select * from dept. and the SQL language compiler automatically generates a procedure to navigate the database and perform the desired task SQL Language SELECT INSERT.ANSI Standard . RENAME.2) NUMBER(7. nonprocedural language . MERGE CREATE. REVOKE Data retrieval Language Data Manipulation Language Data Definition Language Transaction Control Data Control Language To open the isqlplus  http://localhost/isqlplus Desc[ribe] EMP EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO NUMBER(4) VARCHAR2(10) VARCHAR2(9) NUMBER(4) DATE NUMBER(7. UPDATE. ROLLBACK.Structure Query Language (SQL) . DROP.2) NUMBER(2) Desc[ribe] Dept DEPTNO NUMBER(2) DNAME VARCHAR2(14) LOCATION_ID NUMBER(3) Desc[ribe] Locations LOCATION_ID LOC_NAME NUMBER(3) VARCHAR2(13) SQL> select * from emp . DELETE. SAVEPOINT GRANT.Users describe in SQL what they want done. 8 . TRUNCATE COMMIT.

LOCATION_ID 100 200 300 400 SQL* PLUS EDITING COMMANDS SQL> L SQL> select empno from emp . SQL > Spool filename SQL > Spool off . job from emp . SQL > c/emp/dept SQL> L LOC_NAME NEW YORK DALLAS CHICAGO BOSTON SQL > select * from dept . SQL> A . -----------------------SQL > select * from emp . Job SQL > L SQL> select empno . SQL > EXIT Data Retrieval/Query Language (DRL/DQL) (SELECT) General SQL Commands 9 .DEPTNO 10 20 30 DNAME ACCOUNTING RESEARCH SALES LOCATION_ID 100 200 300 400 40 OPERATIONS SQL> select * from locations.sql replace SQL > GET filename SQL > START filename SQL > @ filename SQL > edit filename SQL > Spool on . --------------------------------------------------------------------------------SQL * PLUS File Commands SQL > SAVE filename SQL> save c:\suresh\ss.

sal from emp where sal != 1000.sal + 1000 "Total Salary" from emp. Logical condition SQL> select * from SQL> select * from SQL> select * from SQL> select * from emp emp emp emp where where where where sal > 1000 and job='SALESMAN' . job not in ('SALESMAN'. name. SQL> select ename ||' having Employee Is '||empno from emp.SAL.ename.ename. SQL> select empno. Limiting the Row Selected by comparison condition SQL> select * from emp where empno=7369.sal from emp where sal >= 1000. SQL> select empno.'ANALYST'). SQL> select empno.ename.Inserting rows to dept table SQL> insert into dept (deptno.Putting 0 in place of null values SQL> select empno. Other Comparison Condition SQL> select * from emp where comm is null and mgr is null . SQL> select empno. SQL> select empno..Concating employee no and name column SQL> select empno||' '||ename from emp .'ANALYST'). SQL> select empno. 10 .0) "Total Salary" from emp. SQL> select empno.JOB. SQL> select empno. . adding $1000 to everybodies salary from EMP table with changing the salary column heading SQL> select empno. SQL> select empno.'CLERK') .ename.Display all the rows and columns in EMP table SQL> Select * from emp .ename. SQL> select empno. UPDATE. designation .sal from emp where ename not like 'S%' .sal from emp where job not in ('CLERK'. SQL> select empno. sal > 1000 or job='SALESMAN' .ename.ename.sal from emp where sal between 1000 and 2000 .ename.ename.ename.sal from emp where ename like 'S%' .ename.dname. SQL> select * from emp where sal = any (select sal from emp where deptno=20) . SQL> select empno. --------------------------------------------------------------------------------Data Manipulation Language (DML) (INSERT. job in ('SALESMAN'.ename. MERGE) .ENAME. . DELETE.'dddd') .sal from emp where sal <= 1000.sal + 1000 TotalSalary from emp.loc) values (50.sal + 1000 as TotalSalary from emp.ename.sal.ename. ARITHMETRIC EXPRESSION Display all the Employees of their EMPNO.20) . name.sal from emp where job in ('CLERK'.sal from emp where deptno in (10. Concatenation Operator . SQL> select empno.salary and department no from EMP table SQL> select EMPNO.sal from emp where sal not between 1000 and 2000 .DEPTNO from emp .sal from emp where deptno not in (10.'DDDD'.'CLERK') .ename. sal + nvl(comm. SQL> select distinct job from emp .20).Display all the Employees of their EMPNO.ename. Duplicate Row SQL> select distinct deptno from emp. SQL> select empno.sal from emp where sal > 1000.

&dname.Deleting all rows from emp1 table SQL> delete from emp1 .e. Copy the record from dept to dept1 table SQL> insert into dept select * from dept1 . Delete with subqury SQL> delete from emp1 where deptno in (select deptno from emp1 where deptno=30) .sal.deptno = e. ------------------------------------------------------------------------DATA DICTIONARY LANGUAGE (DDL) ( CREATE.'DDDD'.empno= e. ALTER.Merging Rows create table copy_emp (EMPNO NUMBER(4). &loc) . fname varchar2(30)) . SQL> update emp set sal=sal*2 where deptno=40 and sal > 2000 .ename = e. Rename alter table student add address varchar(100) .dname. Modify.SQL> insert into dept (deptno. . SQL> insert into dept select * from dept1 where deptno=30 . SQL> update emp1 set sal = sal * 2 where deptno in (select deptno from emp1 where deptno=20) . sname varchar2(20).ename . Or SQL> delete emp1. alter table stdeunt add (address1 varchar(100).create a create table student (rollno number(4). c. TRUNCATE.2).deptno). 11 .2) ) . sal number(10. Merge into copy_emp c using emp1 e on (c. DOB date.deptno WHEN NOT MATCHED THEN INSERT VALUES (e.'dddd') . Altering a table by using Add.e. SAL NUMBER(7. RENAME) Creating a table create table Employee (empno number(2). Updating/Changing the existing employee’s information SQL> update emp set sal=sal*2 . c. ENAME VARCHAR2(10). SQL> insert into dept values (50. Delete the rows from emp1 table whose depart no is 20 SQL> delete from emp1 where deptno = 20 .sal.e.empno) WHEN MATCHED THEN UPDATE SET C.empno. Branch varchar2(20)).loc) values (&deptno. ename varchar2(30). ------------------------------------. DROP.sal= e. .ename. DEPTNO NUMBER(2)) . Drop.

A user can grant access to his database object(s) to other user(s) user1 -Granting the select previledge to user2 SQL> GRANT select on emp to user2 user2 User2 is viewing the user1 ‘s emp table select * from user1. Drop table emp1 .To drop multiple columns at a time is: Alter table student drop (FNAME. resource to user2 . Dropping a table Drop table tablename . DROP table tname . open the screen simultaneously. resource to user1 . The synatx for creating a user SQL> SQL> SQL> SQL> SQL> SQL> Create user user1 identified by user1 Alter user user1 identified by user13 . Alter user user1 identified by user23 . address1 varchar2(50)) . . Grant Connect. . branch) . user1 - 12 .alter table student modify (address varchar2(50).Dropping a column in student table alter table student drop column address1 . .The Grant command is used to grant access to the database . . Grant Connect. The Grant Command .To renaming a column Alter table emp rename column ename to empname . . Rename emp to emp1 .To seeting the Unused columns SAL in EMP table Alter table emp set UNUSED COLUMN Sal. Renaming a table Rename oldtablename to newtabalename.emp . Create user user2 identified by user2 . Truncating a Table truncate table dept.Dropping the unused columnfrom the EMPtable Alter table emp DROP UNUSED COLUMNS. REVOKE) Database Security and Previleges Create 2 users. DATA CONTROL LANGUAGE (DCL) (GRANT.

Functions are also capable of accepting user-supplied variables or constants and operating on them. ORACLE FUNCTIONS Oracle functions serve the purpose of manipulating data items and returning a result. Like function_name (arguments1. Accordingly.emp set ename='ffff' where empno=7900 . REVOKE Using the REVOKE command.emp set ename='ffff' where empno=7900 .….update user1. SQL> Rollback.select * from user1. revoke select. a DBA can revoke database privileges from the user(s) user1 User1 is revoking the select previledge from user2 on emp table Revoke select on emp from user2 user2 .. Rollback. arguments2. create session to suresh with admin option. SQL> Rollback to savepoint a . The SAVEPOINT Command Savepoints statements are used to discard or commit all the changes upto a point SQL> Savepoint a . DBA can give Grant create table.) Oracle Function can be clubbed together depending upon whether they operate on a single row or a group rows retrieved from a table.update user1. Such variables or constants are called arguments. TRANSACTION CONTROL LANGUAGE (TCL) (Commit.GRANT update on emp to user2 user2 . user1 revoke update on emp from user2 user2 . The ROLLBACK Command The ROLLABCK command is used to discard parts or all the work the user has done in the current transaction To undo the previos command from after the commit . in suresh grant create table to user1 .emp .update on emp from suresh with grant option . Savepint) The COMMIT Command The commit command is used to make changes to data (DML) permanently SQL> Commit. functions can be classified as follows: Group Functions (aggregate function) 13 .

LENGTH. select empno.'CCCC') from dual .4567. Select avg(sal) from emp . power(3.'*') from emp . greatest('ASSASA'. select empno.'FRIDAY'). USING CASE Expression 14 . Select sum(sal) from emp . which calculates the total set of numbers.last_day(hiredate) from emp .10. ename from emp where rowid=CHARTOROWID('AAAH2CAABAAAPAAAAK') . Scalar Functions (Single Row Functions) Functions that act on only one value at a time are called Scalar Functions. ascii('s').'w') from dual . is a function.add_months(hiredate.hiredate.2) from dual .months_between(sysdate.3) from emp . Aggregate function Select max(sal) from emp .ascii('S') from dual .3).'A') from emp .hiredate. select count(*) from emp .3) from emp. ename.2) from dual . last_day(hiredate) from emp . concat('Hello'. next_day(hiredate. sqrt(25) from dual .'*') from emp . lower(ename) from emp . For example.next_day(hiredate. lpad(sal. concat(empno. trunc(10. SUM.hiredate.Functions that act on a set of values are called set of values are called Group Functions.hiredate.hiredate).'DDD'.hiredate. substr(ename. chr(67) from dual. chr(67)||chr(65)||CHR(84) from dual. is a function. select empno.4567. instr('helloworld'. round(10.'FRIDAY') from emp .10. Date Functions select empno. A group function returns a single row for a group of queries rows. upper(ename) from emp . initcap(ename) from emp .ename) from emp .2) from dual .'World') from dual .instr(ename. lower('Sql Cousre') from dual . String Functions select select select select select select select select select select select select select select select select select select length('SURESH') from dual .months_between(sysdate. which calculates the length of one particular string value.1016) from dual . dump('abc'. A single row function returns one result for every row of a queried table or view. select empno. For example.add_months(hiredate. rpad(sal. Select min(sal) from emp .1.hiredate) from emp . Numeric Functions select select select select select abs(-15) from dual .

ename. SELECT TO_CHAR(sysdate.job.sum(sal) from emp group by rollup(deptno.job. level Command--> select level.sum(sal) from emp group by cube(deptno.job. select to_char(sysdate. 2*sal.job.mgr. select to_number('3456') +1 from dual .count(*) from emp group by deptno .ename.job) .job .mgr.'DD-MON-YYYY HH24:MI:SS') from dual . max(sal) from emp group by deptno. select to_number('3456') +1 from dual . Aggregate functions rea used to return summary information for each group. 4*sal.List the department no and maxumim salary of employees in each department no select deptno. empno.'dd-mm-yyyy') from dual . Group By Clause The Group By clause is used with SELECT to combine a group of rows based on the values of a particular column or expression.job) . 'MANAGER'. case job when 'SALESMAN' then 2*sal when 'CLERK' then 3*sal when 'PRESIDENT' then 4*sal when 'MANAGER' then 5*sal else sal*3 end "Revised Salary" from emp .job order by deptno.'mm/dd/yyyy') from dual . uid from dual. select empno. select deptno.select ename. sal) "Revised Salary" from emp.job . rank() over (partition by deptno. select deptno. 'SALESMAN' . decode (job.job.List the department no and number of employees in each department no SQL> select deptno. job order by sal desc) "R" from emp. max(sal) from emp group by deptno. 5*sal. select upper(rtrim(ename)) + ' working as a ' + upper(rtrim(job)) from emp . select user. mgr from emp start with mgr is null 15 . Conversion Functions TO_DATE: Converts character field to a date type TO_CHAR: date type to character type TO_CHAR: number type to character TO_NUMBER: Converts character to a number data type select to_date('01/01/2005'. . . USING DECODE Function select ename.deptno. 3*sal.'dd/mm/yyyy') from dual . select lower(ename).max(sal) from emp group by deptno .upper(ename) from emp . select deptno. 'PRESIDENT' .sal. select to_date('23-05-2005'.job . 'CLERK' .job. select deptno.sal. max(sal) from emp group by deptno. The aggregate functions are applied to the individual groups. select deptno.

Domain Constraint : .ename. at the time of insertion when no value is given for that column REFERENCES: Assigns a Foreign Key constraint to maintain “Referential Integrity” ON DELETE CASCADE: Using this option whenever a parent row is deleted then all the corresponding child rows are deleted from the details Tbale.sum(sal). Constraints are preferred Rules applied on thable columns while creating or after creation These are automatically activated whenever DML statement is performed on a table Provies high security Integrity Constraints are three types 1. Unique 2.1 . max(sal) from emp group by deptno having count(*)> 5 Note: The WHERE clause cannot be used to restrict the groups that are returned. but only one column per table is allowed CHECK: Controls the value of a column(s) being inserted DEFAULT: Assigns a default value for the column(s). -. Constraints super control the data being entered into a table for permanent storage.Check for conditional rules ex:.sal empno.ename. Avg(sal) from emp where deptno=20 group by job having avg(sal) > 1000 order by sum(sal). min(sal).ename. restrict the groups that you return on the basis of aggregate functions.primary key. maximum and minimum salary and the avrage salary of emplyees job wise department no 20 and sipaly only those rows having average salary greater than 1000. The output should be arranged in the descending order of sum(sal). Integrity Constraints • • • • • Constraints are enforced on data being stored in a table.connect by prior empno=mgr Order by level. List the average salary for all department employing more than five people.sal empno. This option is always used with foreing key. empno asc. Order By Clause ORDER BY Clause will arrange the final result in the order specified select select select select empno. select deptno.sal empno. ename desc. 3.check for uniqueness of data ex. Example Create a table using Primary Key and Not null constraints 16 .2. that is.ename. are called Constraints.sal from from from from emp emp emp emp order order order order by by by by ename asc . We can only use where to restrict individual rows.List the total salary. The Having Clause HAVING clause is used to specify which group are to be displayed.Entity Integraty: . Referential Constraint : Used bind relation between tables NOT NULL: Prevent a column from accepting NULL values UNIQUE : Ensures uniqueness of the values in a column PRIMARY KEY : Same as UNIQUE. Max(sal). Not null 3. ename desc. SQL> select job.Check.

the retrieval criteria will typically specify the condition that a column in the first table (which is defined as a foreign key) is equal to a column in the second table (which is the prrimary key Types of Joins Oracle Proprietary Joins (8i and Prior) . sal number(5. on delete Note: If a user is not giving the constraint name.constraint)type table_Name=’TABLENAME’ . To see details about the infomration of constraints SQL> desc user_constraints SQL> select constraint_name. the information from any number of tables can be accessed.Non-equi join . .Inner Joins . deptno number(2) not null.2) check (sal > 0) . create table department (deptno number(2) primary key . primary key. create the master table first and after that child table.For foreign key . alter table employee add constraint Dept_pk primary key (deptno) . dname varchar2(30) not null.Natural Joins . constraint Emp_pk_id primary key (empno)) . To join two tables.Outer Join .Full or two side outer joins 17 . constraint EmpNO_fk foreign key (deptno) references department(deptno) cascade) . ename varchar2(30) not null. deptno number(2) . Oracle automatically create a constraint named as “SYS_C0 (some number)” Dropping the Primary key constraint SQL> alter table employee drop primary key .Creating a table using foreign key.Self Join SQL: 1999 Complaint Joins: .Equi join -Cartesian Joins .Cross Joins . Job varchar2(30) unique . check and default constraint create table employee (empno number(4) primary key. . unique . ename varchar2(30) not null. Job varchar2(30) unique . from user_constraints where JOINS Joins. or alter table employee drop constraint constraintname.Using Clause Joins .create table employee (empno number(4). location varchar2(30)) . DOJ date default sysdate.

emp manager where worker . select WORKER.dname from emp cross join dept .ename. SQL> select * from emp.location_id .emp. Such rows can be forcefully selected by using the outer join symbol (+).dept. The table is not actually copied.deptno (+) . from emp.hisal .dname from emp. each row of one matches every row of the other table. Non-Equi-joins: select e. select emp.j.loc_Name from emp e. dept where emp.dept.e.dname emp.empno.dname.dname from emp.sal between j. Cross Join select ename.deptno (+) = dept. 18 .Joins with the ON Clause Equi –Joins When two tables are joined together using equality of values in one or more columns. This results in a Cartesian product. dept .deptno=dept. Joining More Than two Tables select e.deptno and e.d.d. The corresponding columns for that will have NULLs.dept.name. but SQL performs the command as through it were.empno. dept where emp.ename.deptno = dept.deptno=20 .empno.dname from emp e.deptno=20 .deptno=d. Self-joins To Join a table itself means that each row of the table is combined with itself and with every other row of the table.emp.. Using (+) operator Outer-joins If there are any values in one table that do not have corresponding value(s) in the other. The self join be viwed as a join of two copies of the same table.e. dept where emp.ename.deptno and emp. in an euqi join that row will not be selected.losal and j.location_id=l. then the total number rows produced is 56. l. select ename.ename.dname from emp. Using Table Aliases select e.ENAME “Manager” from emp worker.ename.ename.empno. select emp.sal.emp.deptno .empno. This is also called as Simple Joins or Inner Joins .dept. Locations l where e.empno .deptno .deptno=d. MANAGER.mgr=manager.grade from emp e . If the number or rows in emp Table is 14 and dept table has 4 . dept . dept where Using AND Operator select emp.emp.deptno=dept.empno. dept d. dept d where e. Cartesian Joins When no join condition clause is specified in WHERE clause.dname from emp. they make an Equi Join.e. salgrade j where e.Primary Key and Foreign Key select emp.ENAME.deptno and d.

dname from emp e full outer join dept d on (e. Left Outer Joins Select e.empno.location_id.ename.ename.ename.Rows of first query plus rows of second query.The NATURAL JOINS clause is based on all columns in the two tables that have same name select deptno.deptno=d.deptno . select e.deptno from emp e join dept d ON (e. dept where dept.e.d.deptno) .ename.location_id.d. earlier: select emp.ename.loc_name from dept natural join locations .loc_name from emp e join dept d ON (e.l.Natural Join .deptno=d. select deptno.dname from emp e inner join dept d on (e.The natural join and using Clauses are mutually exclusive select l.deptno=d.deptno.deptno=d.empno.deptno. select e. less duplicate rows union all .empno.Rows of first query plus rows of second query.location_id) .dname from locations l join dept d using (location_id) where location_id=100 .Do not use a table name ot alias in the referenced columns . Creating Three-Way Joins with the ON Clause select e.deptno) .deptno.ename.ename. d.ename from emp e Join emp m on (e. Set Operator Set Operators are used to combine information of similar type from one or more than one table Data types of corresponding columns must be the same The types of SET operators in ORACLE are: Union: . you can not write l.dname from emp e right outer join dept d on (e.same as equi joins Creating Joins with the ON Clause .deptno (+)= emp.d.e.d.dname from emp e left outer join dept d on (e.dname. m.e.dname from emp.The join condition for the NATURAL JOIN is basically an equijoin of all columns with the same name.e.dname from emp.d.deptno=d. Right Outer Joins select e.dname. 19 . dept where dept.dname.deptno=d.location_id=l.deptno) .deptno (+) .empno=m.ename.deptno. with duplicate rows Intersection – Common rows frm all the queies Minus – Rows unique to the first query UNION select * from emp union select * from emp1 .dept.deptno) join locations L ON (d.20) . Creating Joins with the USING Clause .location_id = 1400 .emp.e.loc_name .e. Full Outer Joins select e.deptno) .loc_name from dept natural join locations where deptno in (10. Inner Joins Select e.deptno) .dept.emp.mgr) .deptno = emp.e. earlier: select emp.empno.ename.

deptno and e. . Using Sub Query in the From Clause select e. =. including .salavg . select sal from emp where sal < all (select avg(sal) from emp ) .The result of the sub query is used by the main query (Outer query). INTERSECT select * from emp intersection select * from emp1.e.UNION ALL select * from emp union all select * from emp1. select ename.Compare Value to every value returned by the subquery (IN) select ename.Equal to any members in the list ANY .job from emp where deptno = (select deptno from emp where empno=7902) .The WHERE Clause . You can build powerful statements out of simple ones by using sub queries. >. avg(sal) salavg from emp group by deptno) b where e. <>) Multiple row operators (IN. Comparison conditions falls into two classes: Single row Operators (<. >=. Multiple Row Sub Queries IN .sal.sal from emp where sal > (select avg(sal) from emp). SUB QUERIES Sub query: A sub query is a SELECT statement is embedded in a clause of another SELECT statement.The sub query (inner query) executes once before the main query. They can be very useful when need to select rows from a table with a condition that depends on the data in the table itself: You can place the sub query in a number of SQL clause.deptno=b.b.sal from emp where sal > (select sal from emp where ename='SMITH') and deptno = (select deptno from emp where ename='SMITH') .The HAVING Clause .The FROM Clause . ALL) Single Row Sub Queries select ename.Compare Value to each value returned by the subquery ALL . Using Group Function in a Subquery select ename.sal > b. Having Clause with Sub queries select deptno.ename. ANY. 20 . <=.salavg from emp e.deptno.min(sal) from emp group by deptno having min(sal) > (select min(sal) from emp where deptno=20) . (select deptno.sal from emp where sal in (select min(sal) from emp group by sal) .e. MINUS select * from emp minus select * from emp1.

SELECT EMPNO.1600) .sal from emp where sal = any (select min(sal) from emp group by sal) ..sal from emp where any < (1200.DEPTNO= (SELECT DEPTNO FROM DEPT WHERE DEPTNO=A.ENAME.DEPTNO).empno) . if the subquery does not produce any output.ename.sal from emp where sal < any (1200. Correlated Sub Query Correlated sub queries are used for row-by-row processing. select ename. 21 .1600).ename. SQL> SELECT ENAME. EXISTS Operator    This operator is used to check for the existence of values This operator produces a Boolean result It takes a subquery as an argument and evaluates it to True. SAL.(ANY) select ename. SQL> SELECT ENAME.DEPTNO). DEPTNO FROM EMP OUTER WHERE NOT EXISTS (SELECT * FROM EMP WHERE DEPTNO= OUTER. List the employees details who do not manage any one.mgr=e.sal from emp where sal < any (select min(sal) from emp group by sal) . SQL> select ename.sal from emp where sal < all (1000. SAL.1600) order by sal . WORKING WITH DATABASE OBJECTS VIEWS VIEWS are Database Objects whose contents are derived from another table .3000) .The changes in the tables are automatically reflected in the VIEWS A VIEW is like a ‘windows’ through which data can viewed or changed.empno) . -----select ename. List all employees who have atleast one person reporting to them SQL> Select empno.sal from emp where sal < all (select sal from emp where job='MANAGER') .job. if the subquery produces any opuput and False. DEPTNO FROM EMP OUTER WHERE SAL > (SELECT AVG(SAL) FROM EMP WHERE DEPTNO=OUTER. (ALL) select empno. DEPTNO FROM EMP OUTER WHERE EXISTS (SELECT * FROM EMP WHERE DEPTNO= OUTER. select ename.job.A VIEW Contains no data of its own .2000.DEPTNO FROM EMP A WHERE A.ename.deptno from emp e where EXISTS (select empno from emp where emp. Each sub query is executed once for every row of the outer query.The command for creating VIEW is CREATE VIEW command .job from emp e where NOT EXISTS (select mgr from emp where mgr=e. select ename.DEPTNO) SQL> SELECT ENAME.DEPTNO ) . SAL. select empno.sal from emp where sal < any (800.

Views with Read Only create view vname as select empno.10) .deptno from emp where deptno=10 with check option .To restrict data access .sal. ename.deptno from emp . alter view vname as select empno.Advantages of a VIEW .ename. Drop view EMPPVIEW1 .'fffff'.deptno.ename.Contains funcions or groups of data .Contains no functions or groups of data . SQL> select rownum as rank.Can perform DML operations through the view A Complex view is one that: .3456. Creating a Force view .Derives data from only one table . create view EmpView as select empno.d.ename. insert into vname values (2345.dname from emp e left outer join dept d on (e. Update and Delete statement in a Simple View SQL>insert into vname (empno.'XYZ'.Does not always allow DML opearations through the view Simple View SQL> SQL> SQL> SQL> create view vname as select empno. select * from EmpView . Complex View . Insert.sal. SQL>update vname set ename='FFFF' where empno=4567 . SQL> Create table blank ( a number) .To make complex queries easy . and then create a table sql> create force view bcd as select * from blank .deptno).ename.ename. SQL>delete from vname where empno=4567 . create view vname1 as select e.sal from (select ename. VIEWS with Check Option create view vname as select empno.deptno) values (4567.deptno=d.e.sal from emp order by sal desc) where rownum <= 3 . 22 .sal from emp where empno=7900 .Creating a View using Group by function SQL> create or replace view emppview1 as select deptno.50) .ename.To present different views of the same data A Simple View is one that: .ename.Derives data from many tables . count(*) total from emp group by deptno .deptno from emp where deptno=10 with read only .Creating a view with out the table existing Create a view first.To provide data independence .deptno from emp .

nextval from dual .Can reduce disk I/O by using a rapid path access method to locate data quickly.) Bitmap indexes. SQL> select Dept_seq . last_number from INDEXES An Index: . which store rowids associated with a key value as a bitmap Partitioned indexes. (By default. Automatically: A unique index is created automatically when you define a PRIMARY KEY or UNIQUE constraint in a table definition.max_value. which consist of partitions containing an entry for each value that appears in the indexed column(s) of the table Function-based indexes.min_values. increment_by. They enable you to construct queries that evaluate the value returned by an expression. which are instances of an application-specific index of type indextype SQL> CREATE INDEX EMPIDX on emp (empno) . SQL> Drop sequence Dept_seq .currval from dual . select * from bcd . which are based on expressions. user_sequences . Oracle Database creates B-tree indexes. SEQUENCES A Sequence: Automatically generates unique numbers Is a sharable object Is typically used to create a primary key value Replaces application code Speeds up effeciency of accessing sequence values when cached in memory SQL> create sequence Dept_seq increment by 10 start with 120 MAXVALUE 9999 . insert into blank values (33) . SQL> select Dept_seq . Manually: Users can create non-unique indexes on column to speed up access to the rows. 23 . Domain indexes.SQL> SQL> SQL> SQL> insert into blank values (33) . which in turn may include built-in or user-defined functions. SQL> DESC bcd Dropping a View SQL> Drop view viewname . SQL> select sequence_name. Oracle Database supports several types of index: • • • • • Normal indexes.Is used by the Oracle Server to speed up the retrieval of rows by using pointer. insert into blank values (33) . .

BASED INDEXES . SQL> DROP synonym dept. rows with identical column values are kept together on disk in the same area. SQL> create table emp2 (empno number(4) primary key. SQL> drop cluster emp_add including tables . For the tables in a cluster. SQL> create cluster emp_add (empno number(4) ) . address varchar2(20)) cluster emp_add (empno) .dept. It requires at least one cluster column from each of the tables. address varchar2(20)) cluster emp_add (empno) . SQL> Drop Index Upper_dept_idx . address varchar2(20)) cluster emp_add (empno) . Dropping a Index SQL> Drop Index <IndexName> . . SQL> create table emp_address1 (empno number(4) primary key. Delete the cluster item 24 . SQL> create table emp_address (empno number(4) primary key. the same logical block(s).Shorten lengthy object names SQL> Create synonym dept for scott. SYNONYMS Simplify access to objects by creating a synonym. These must be of the same data types and size.FUNCTION . CLUSTER Clustering is a method of storing tables that are intimately related and often join together into the same area on disk.Ease referring to a table owned by another user . SQL> create index emp_address on cluster emp_add . SQL> select * from dept. This clauses improvement of performance when the cluster columns are the columns by which the tables are generally joined. but are not required to possess identical names.A function-based index is an index based on expressions. BIT MAP INDEXES SQL> CREATE BIT MAP INDEX EMPIDX on emp(sex) . SQL> Create Index Upper_dept_idx on dept (upper(deptno)) . ename varchar2(30).

List partitioning Range Partitioning Use range partitioning to map rows to partitions based on ranges of column values. an application can be programmed to take advantage of partitioning by using partition-extended table or index names in DML. sal number(8. Partitioning Method There are several partitioning methods offered by Oracle Database: .Range partitioning . 'VM'. SQL> create table emp345 (empno number(3) primary key.Hash partitioning . SQL> CREATE TABLE Dept_part (deptno number. 'UT'. 25 . PARTITIONS Storing partitions in separate tablespace enables you to: ----Reduce the possibility of data corruption in multiple partitions ----Back up and recover each partition independently ----Improve manageability. availability. deptno number(2)) Partition by range (deptno) (Partition p1 values less than (10) tablespace tbs1. 'NM') tablespace tbs2. ename varchar2(30). Partition p3 values less than (30) tablespace tbs3. PARTITION q4 VALUES ('FL'. Partition p4 values less than (40) tablespace tbs4) List Partitioning Use list partitioning when you require explicit control over how rows map to partitions. PARTITION q3 VALUES ('NY'. PARTITION q2 VALUES ('AZ'. 'WA') tablespace tbs1. and performance ----Partitioning is transparent to existing applications and standard DML statements run against partitioned tables.2). Partition p2 values less than (20) tablespace tbs2. 'GA') tablespace tbs4). You can specify a list of discrete values for the partitioning column in the description for each partition. However. 'NJ') tablespace tbs3.SQL> drop index emp_address . state varchar2(2)) PARTITION BY LIST (state) (PARTITION q1 VALUES ('OR'. deptname varchar2(20).

To Create HASH Partition SQL> create table purchases (inv_no number . Coalescing a Partitioned Table ALTER TABLE emp345 COALESCE PARTITION. Moving a Partitions ALTER TABLE emp345 MOVE PARTITION p4 tablespace tbs4 . year) (partition h1 tablespace ts1. Dropping a Table Partition Alter table emp345 drop partition p5. Table Level Locks --> Row Level Locks: This lock is used to lock either a single or group of records. LOCKING MECHANISM Locks : Locks are of two types. Row Level Locks 2. Hash Partitioning dba_tab_subpartitions where Hash partitioning provides a method of evenly distributing data across a specified number of partitions.SQL> select tablespace_name.for the rest of the numbers & entities he can do manipulation Ex: Select * from emp for update of comm. year number) partition by hash (day. Renaming a Table Partition ALTER TABLE emp345 rename PARTITION p4 to p45 . 1. Merging Partitions ALTER TABLE emp345 MERGE PARTITIONS p1 . Rows are mapped into partitions based on a hash value of the partitioning key. for the purpose of updations. day number. note: another user cannot manipulate comm&sal of 7788. partition h3 tablespace ts3). month number. Adding a Partition to a Partitioned Table alter table emp345 add partition p5 values less than (50) tablespace tbs4 . It controls the physical placement of data across a fixed number of partitions and gives you a highly tunable method of data placement.sal. Truncating Partitions alter table emp345 truncate partition p5 . month. A Row Level Lock is implemented with in a select query using "for update of " clause. Ex: Select * from emp where empno=7788 for update of comm. p2 into PARTITION p6 . partition h2 ta blespace ts2. sal. 26 . partition_name from table_name='emp_sub_template' order by tablespace_name.

ename. Lock table emp in share mode.ename from emp where job = '&job' .Double ampersand (&&) . Using DEFINE Command 27 . Specifying Column Names.ename from emp where empno = &empno .. For Character or date select empno.g. -> Exclusive Lock : When a user locks a table in Exclusive mode.g. Expressions and Text select empno.g.Note: another user cannot manipulate comm&sal all the numbers. but still is used to lock records.e. when it ends 2nd user can use it for manipulations. Lock table emp in Exclusive Mode.DEFINE command Using the & Substitution Variable For Integer select empno. -> Share Lock -> Share Update Lock -> Exclusive Lock -> Share Lock : This is a sharable lock. multiple users can implement this sharable lock on a single table at the same time.job.. for the rest of the entities he can do manipulation Ex: Select * from EMP for update. E. E. -> Share Update Lock: Even though this lock fall under Table Level locks. note: the 2nd user who didn`t lock the table which is locked by the first user should wait uptill the 1st user`s end transaction.. i. note: another user cannot manipulate all the entities of the table Note: only manipulations r not allowed but he can retrive values (select)of the table --> Table Level Locks: These are further classified into three caregories. to use this lock first we need to lock the required records using row level lock and then implement this lock.Single ampersand (&) .&column_name from emp where &condition order by &Order_column . no other user can access that table except the user who has locked it in Exclusive mode. but the 1stuser need not wait for the 2nd user`s end transaction E. More Commands In Oracle 9i Substitution Variables Temporarily Store Values . Lock table emp in share update mode.

job.30) .sal.hirdate) values (222.ename.hiredate. Conditional INSERT ALL INSERT ALL WHEN SAL > 10000 then INTO sal_history values (empno.ename.deptno from emp where empno=&empno .default) .sal) INTO mgr_history values (empno.ename.deptno from emp where empno= &empno . Using the && Substitution Variable select empno.sal) select empno.N Analysis select rownum as rank.sal. SQL Sample Report set feedback off TTITLE 'EMployee|Report' BTITLE 'Confidential' BREAK ON JOB COLUMN JOB HEADING 'JOB|Cattegory' COLUMN ename HEADING 'EMPLOYEE NAME' COLUMN sal HEADING 'SALARY' select job.job.sal from emp where sal < 5000 order by job.deptno from emp where deptno=20 with check option) values (2222. Using Sub query in an INSERT Statements with check option insert into (select empno.ename. Performing TOP .'MANAGER'.sal from emp order by sal desc) where rownum <= 3 .mgr.DEFINE empno=7902 .sal. Using Verify Commands set verify on .mgr from emp where empno > 1000 .ename.&&column_name from emp order by &column_name .hiredate.hiredate.'MANAGER'. ename. select empno.30) . Using Explicit Default Values insert into emp (empno.'ddddd'.ename.ename.sal from (select ename.deptno from emp where deptno=20) values (2222. Unconditional INSERT ALL INSERT ALL INTO sal_history values (empno.job.sal.'dddd'.ename.'ddddd'.3333.sal) 28 .sal set feedback on COLUMN JOB clear COLUMN ename clear COLUMN sal clear clear Break Using Sub query in an INSERT Statements insert into (select empno. select empno.

sales_THU) (empno.week_id.sales_WED) (empno.sal) select empno.sales_FRI) from select empno.sales_tue.WHEN MGR > 200 THEN INTO mgr_history values (empno.sal. 29 .sales_mon) (empno. 3. Improved performance. Pivoting Insert INSERT ALL INTO sales_info INTO sales_info INTO sales_info INTO sales_info INTO sales_info values values values values values (empno. 4.hiredate. 2. Improved code clarity. Easy Maintenance Improved data security and integrity.mgr from emp where empno > 1000 . Blocks of PL/SQL code are passed to and processed by a PL/SQL engine. You can program with procedural language control structures. Improved Performance Benefits of Subprogram 1.week_id.mgr. You can declare variable.week_id.sales_thu. PL/SQL Architecture Benefits of PL/SQL PL/SQL is portable. PL/SQL can handle errors.sales_fri sales_source_data .sales_wed.week_id.week_id.sales_mon.week_id. PL/SQL Introduction to PL/SQL -PL/SQL required for data processing -It is a procedural language extension to the non-procedural SQL.sales_TUE) (empno.

Using %TYPE . V_orderdate date := sysdate + 7 .The database table and column .job%type . variables for the entire row of a table need to be declared.The previously declared variable name . The record can store an entire row of data selected from the table or fetched by a cursor (declared later). the attribute %type is used EMP_ROW_VAR EMP%ROWTYPE: 30 . then instead of declaring them individually. In case. v_job emp.PL/SQL statements Exception (Optional) Actions to perform when errors occur End. Declaring PL/SQL Variables := (assign operator) DECLARE v_hiredate date. user-defined exception Begin (Mandatory) . Using %ROWTYPE The %ROWTYPE attribute provides a record type that represents a row in a table (or view). end . begin select empno into mempno from emp where empno=1000.ename%type . Naming Rules DECLARE memp_id number(4):= 1000 .Declaring Variables with the %TYPE Attribute v_Name emp. v_valid BOOLEAN NOT NULL := TRUE . Base Scalar Data Types CHAR VARACHAR2 LONG LONG RAW NUMBER BOOLEAN Scalar Values Declaration Declare V_job Varchar(10) . v_deptno number(2) := 10 .SQL statements .PL/SQL Block Structure DECLARE (Optional) Variables. cursor.

BEGIN select sal into :g_salary from emp where empno=7902 . end . the variable EMP_ROW_VAR will be a composite variable. dbms_output.. v_conat varchar2(30. the following syntax will be used: EMP_ROW_VAR.. dbms_output. consisting of the column names of the table as its members.sal := 2000 ... end . Print g_salary For Printing the values :.DBMS_OUTPUT. begin v_conat := V_ename || V_sal . Begin . z number . begin Declare Y Number...put_line('The monthly salary' || v_sal ) .sal%type. dbms_output. Declare v_sal begin v_sal = v_sal /12 . End .. DEFINE p_anual_sal = 60000 . begin z:= x+y .... V_sal emp. end ..PUT_LINE set serveroutput on . y number:=56 .Put('the value of z is '||x) . To refer to a specifiec variable.. Nested Block Declare x number. sal SAL.Put_line('the value of z is '||y) .Here. Using BIND Variables VARIABLE g_salary number .. Commenting Code /* */ declare V_ename emp.. Some Sample Progamme using PL/SQL Block declare x number:=45 . 31 . .empno%type . end .

begin delete from emp where deptno= v_deptno .'EDP'. end.deptno%type := 50 . mename emp.deptno%type := 50 . end. dbms_output. Manipulating data Using PL/SQL Make Changes to database tables by using tables. Operators in PL/SQL --Logical --Arithmetic --Concatenation Same as SQL -----------------------Select Statement in PL/SQL --------------------------. begin delete from dept1 where deptno=v_deptid .empno%type .Put_line('The sasasasasa').Put_line('the value of z is '||z) . ------------------------------------------------------------------------declare v_deptid dept1. Insert delete Update Merge Insert command using begin insert into dept1 (deptno.mename from emp where empno=7902.dbms_output.sal%type := 200 .The Into clause declare mempno emp.'America') . end. begin select empno. Delete command using declare V_deptno emp.ename%type .loc) values (50. Update command using declare V_sal_inc emp.ename into mempno. begin update emp set sal = sal + v_sal_inc where deptno= 50 . end.dname. 32 . end .

end if . end if . if msal > 100 and msal <= 2000 then a:='Salary is between 1000 and 2000'. Example : if v_name='KING' then v_job := 'President' . end . -------------------------------------declare mempno emp. 33 . elsif msal > 2000 and msal <= 3000 then a:='Salary is between 2001 and 3000'. else v_job := 'Clerk' . end . msal emp.put_line (sql%rowcount || 'Row deleted') . begin select sal into msal from emp where empno=mempno. Conditional and Iterative Control The conditional control available with PL/SQL are: IF-THEN –ELSE statement The type of Loops available with PL/SQL 1) Basic Loop 2) While Loop 3) For Loop IF STATEMENTS Syntax: IF <condition1> then <statement1> elsif <condition1> then <statement1> else <statement1> end if.sal%type. a varchar2(100) . else a:='Salary is greater than 3000' . Basic Loop The syntax is.dbms_output. LOOP <Statement> exit [loop-label] [WHEN Condition] end loop .empno%type:=&empno . elsif v_name='JONES' then v_job := 'Manager' .put_line(a) . dbms_output.

end loop.. Example declare i number:= 1 . end. begin for i in 1.. v_appraisal varchar2(30) . begin v_appraisal := CASE v_grade WHEN 'A' then 'Execllent' WHEN 'B' then 'Very Good' WHEN 'C' then 'Good' else 'No Such Grade' end. i := i+1 .put_line(i) . i := i+1 . end loop. end .put_line(i) .put_line ('Grade: ' ||v_grade|| ' Appraisal ' ||v_appraisal) .put_line(i) . exit when i > 10 . begin while I < 11 loop dbms_output. FOR Loop The Syntax is : FOR <var> IN <lower>. end . 34 . dbms_output. end . begin loop dbms_output. end loop. WHILE [condition]LOOP <Statement> end loop . Using CASE EXPRESSIONS declare v_grade char(1) := upper( '&V_grade') .Example: declare i number:=1 . WHILE Loop The syntax is.10 loop dbms_output.<upper> LOOP <Statement> End loop Example declare i number .

put_line ('Grade: ' ||v_grade|| ' Appraisal ' ||v_appraisal) .V_ename. else dbms_output. Close the Cursor -Declaring the Cursor CURSOR emp_cursor is Select empno. begin x:=&x. end. z number. end.ename from emp . 3. v_appraisal varchar2(30) .put_line('Wellcome'). dbms_output. This work area is private to SQL’s operations and called a Cursor. z:=x+y. y number.V_sal. begin v_appraisal := CASE WHEN v_grade ='A' then 'Execllent' WHEN v_grade ='B' then 'Very Good' WHEN v_grade = 'C' then 'Good' else 'No Such Grade' end. <<pqr>> dbms_output. end if. Controlling Explicit Cursors 1. Using GOTO Statement declare x number. Fetch a row. Open the Cursor 2.-----Same program but we can write some other way declare v_grade char(1) := upper( '&V_grade') . if z>=50 then goto pqr. -Fetching Data from the Cursor Fetch emp_cursor into v_empno. Cursor The Oracle Engine uses a work area for its internal processing in order to execute an SQL statement. -Closing the Cursor 35 .put_line('fjbfbfbb'). Two Types Cursor A) Implicit: Declared for all DML and PL/SQL SELECT statements B) Explicit: Declared and named by the programmer. -Opening the Cursor OPEN emp_cursor . y:=&y.

begin Open emp_cursor . Same Program using %notfound (Implicit Cursor ) declare v_empno emp. end.empno%type. v_sal emp. '||v_sal).10 loop fetch c1 into v_empno.put_line (v_empno||' '||v_sal).10 loop fetch emp_cursor into v_empno. LOOP fetch emp_cursor into v_empno. v_ename emp. cursor c1 is select empno. begin open c1. end. dbms_output. cursor emp_cursor is select empno..Evaluates to the total number of rows returned so far. ---------------------------------------------------------------------------declare 36 . exit when c1%notfound.sal%type .Evaluates TRUE if the Cursor Open %NOTFOUND .v_sal . for i in 1.empno%type. v_sal emp. cursor emp_cursor is select empno.sal from emp. end.ename.sal%type . for i in 1. end loop. v_sal emp.Evaluates TRUE if the most recent fetch return a row %ROWCOUNT .empno%type.put_line('The Employee No: ' ||v_empno||' and name is ' ||v_ename|| ' The salary is' ||v_sal).put_line (v_empno||' end loop.sal from emp .V_ename. Examples Using BASIC LOOP declare v_empno emp.v_sal. exit WHEN emp_cursor%rowcount > 10 or emp_cursor%notFOUND. dbms_output.sal from emp. Using FOR LOOP declare v_empno emp.sal%type . begin open emp_cursor. Close emp_cursor.ename%type . Explicit Cursor Attributes %ISOPEN . dbms_output..v_sal.Evaluates TRUE if the most resent fetch does not return a row %FOUND . End LOOP .Close Emp_cursor .

mename emp.ename%type ; msal emp.sal%type ; mjob emp.job%type; mempno emp.empno%type; cursor c1 is select empno,ename,job,sal from emp ; begin open c1; loop fetch c1 into mempno,mename,mjob,msal; if msal < 2000 then update emp set sal=msal*2 where empno=mempno; dbms_output.put_line(mempno||' '||mename||' '||msal*2||' '||mjob) ; elsif msal between 2000 and 4000 then update emp set sal=msal*.5 where empno=mempno; dbms_output.put_line(mempno||' '||mename||' '||msal*.5||' '||mjob) ; elsif msal > 4000 then update emp set sal=msal*.2 where empno=mempno; dbms_output.put_line(mempno||' '||mename||' '||msal*.2||' '||mjob) ; end if ; exit when c1%notfound ; end loop ; close c1 ; end ; FOR LOOP Declare cursor c1 is select empno,ename,deptno from emp; begin for emp_record in c1 loop if emp_record.deptno=20 then dbms_output.put_line('Employee No ' ||emp_record.empno emp_record.ename); end if; end loop; end; Implicit Cursor Attributes SQL%ISOPEN - Is always false because Oracle automatically close an Implicit cursor after executing its SQL statement SQL%NOTFOUND - Evaluates TRUE if the DML statement was not suceesful %FOUND - Evaluates TRUE if the DML statement was suceesful %ROWCOUNT – Returned to the total number of rows affected by an INSERT,UPDATE, DELETE or single row SELECT OPEN, FETCH, CLOSE : cannot be used to maipulating the implicit cursor SQL

||'

Name

is

'||

Cursor with parameter
-Pass parameter values to a cursor when the cursor is opened and the query is executed -Open an explicit cursor several times with a different active set each time. Syntax CURSOR cursor_name (parameter name data type) is select statement Begin Open cursor_name (parameter values) End ;

37

- Paremeter data types are the same as scalar data type but do not give them sizes. Example: declare mename emp.ename%type; mempno emp.empno%type; cursor emp_cursor (mdeptno number, mjob varchar2) is select empno,ename from emp where deptno=mdeptno and job=mjob; begin for emp_record in emp_cursor (30,'SALESMAN') loop fetch emp_cursor into mempno,mename ; dbms_output.put_line(mename||' '||mempno); end loop ; end; --------------------------------Cursor with Subqueries Subquery returns a value or set of values to outer query. Syntax Cursor emp_cur is select empno, ename, sal from EMP where deprno in (select deptno from dept) Defining REF Cursor Type - Explicit cursor is a static cursor - It is always refers only one work area in memory - REF CURSOR is dynamic cursor - It is like a pointer in C - It refer different work area in memory at run time more than one SQL statement can be associated to ref cursor at run time. - Cursor variable is like a pointer define with REF type Types of REF CURSOR STRONG REF CURSOR – the REF CURSOR which is return type WEAK REF CURSOR – the REF CURSOR without return type - Define a REF cursor type: Type ref_type_name is REF CURSOR - Declare a variable of the type ref_cv ref_type_name ; STRONG REF CURSOR Declare Type ref_c is ref cursor return emp%rowtype; C1 ref_c ; Vrec emp%rowtype; Vdno number(2) := &vdno ; Begin If vdno =10 then Open c1 for select * from emp where job=’MANAGER’ ; Elsif vdno = 20 then Open c1 for select * from emp where job=’SALESMAN’ ; Else Open c1 for select * from emp where job=’CLERK’ ; End if;

38

Loop Fetch c1 into vrec ; Exit when c1%notfound; dbms_output.put_line(vrec.empno||’ ‘||vrec.ename) ; end loop; close c1; end; WEAK REF CURSOR declare v_empno emp.empno%type; v_sal emp.sal%type ; v_ename emp.ename%type ; mdname dept.dname%type; type r is ref cursor; emp_cursor r; begin Open emp_cursor for select empno,ename,sal from emp ; LOOP fetch emp_cursor into v_empno,V_ename,v_sal ; dbms_output.put_line('The Employee No: ' ||v_empno||' and name is ' ||v_ename|| ' The salary is ' ||v_sal); exit WHEN emp_cursor%rowcount > 10 or emp_cursor%notFOUND; End LOOP ; Open emp_cursor for select dname from dept ; LOOP fetch emp_cursor into mdname; dbms_output.put_line('The dept name is ' ||mdname); exit WHEN emp_cursor%rowcount > 10 or emp_cursor%notFOUND; End LOOP ; end;

EXCEPTION HANDLING
An Exception is an identifier in PL/SQL that is raised during execution that terminates main body of action. EXCEPTION is raised by two methods - An Oracle error occurs and then associated exception is raised automatically. - Using RAISE statement within the block, the exception being raised may be user defined or predefined EXCEPTION is three type 1) Pre Defined Exception 2) User-Defined Exception 3) Non-Pre Defined Exception 1) Pre Defined Exception The predefined oracle package standard has defined exceptions for certain common errors. Exceptions are handled using names not using error numbers. The errors which are not handles using exception, can be handled usinf exception ‘OTHERS’ Examples Too_many_rows No_data_found Zero_divide others Some Sample Programs Using Pre-Defined Exceptions

39

exception when zero_divide then dbms_output. 3) Using too_many_rows Exception declare mename emp.Put_line(' Too many rows returned') . end.Put_line('The emp name is '||mename||' salary is '||msal) .declared in the declare section of a PL/SQL Block . dbms_output.deptno%type:=&deptno.put_line('no record found').sal%type. exception when no_data_found then dbms_output.put_line('more then one error selected').sal into mename. dbms_output.put_line('wellcome').put_line('Invaild empno') . end.sal%type .msal from emp where empno=7902 . dbms_output. end. begin select sal into x from emp where deptno=y. dbms_output.sal%type.msal from emp where deptno=30 .Put_line(z) . end. msal emp.put_line('sal of empno is='||x). y number(2):=0 . begin select ename. end if. y emp.Put_line('The values is divided by Zero') . exception when too_many_rows then dbms_output. msal emp. if sql%rowcount > 0 then dbms_output. 4) Using too_many_rows and others Exception declare x emp.ename%type. begin select ename. when others then dbms_output.ename%type . 2) Using zero_divide Exceptions declare x number(2):=22 .sal into mename.put_line(mename||msal) . exception when too_many_rows then dbms_output. User Defined Exception User defined exceptions must be .Raised Explicitely with RAISE statements 40 . z number .1) Using no_data_found Exception declare mename emp. begin z:=x/y .

RAISE_APPLICATION_ERROR can be used in either the executable section or exception section of a PL/SQL program.put_line('sal of empno is='||x).sal%type.put_line('salary is greater than 4000') .empno%type:=&empno. 2) declare x emp. 1) declare v_empno number(4):=&empno . dbms_output. if SQL%NOTFOUND Then RAISE E_invalidDept. end if. begin delete from emp where empno=v_empno . E_invalidDept Exception. sal_exc exception . end if .Put_line(msal) . else dbms_output. y emp.sal%type . end . else dbms_output.ename%type . if SQL%NOTFOUND Then RAISE_APPLICATION_ERROR (-20202. Exception WHEN E_invalidDept then DBMS_OUTPUT. end if .msal from emp where empno=7902 . exception when emp_exc then dbms_output. if x > 3000 then raise sal_exc. if msal > 4000 then Raise emp_exc . 41 . emp_exc exception . msal emp.PUT_LINE('Wrong EMPNO') . 2) declare mename emp.sal into mename. RAISE_APPLICATION_ERROR Procedure: Is used to communicate a predefined exception interactively by defining a non standard error code and error message. begin delete from emp where empno=v_empno . begin select ename. end .Some Sample Programs Using User Defined Exceptions 1) declare v_empno number(4):=7902 . begin select sal into x from emp where empno=y. end.put_line('wellcome').'wrong empno') .

-----------------------------------declare z_divide EXCEPTION . end. PRAGMA EXCEPTION_INIT(t_row_many. exception when e_emp_remaining then dbms_output.put_line('no data found'). is done in the declare section of a PL/SQL block. String). begin z:=x/y.-2292) .'Salary is greater than 3000') . end. The Pragma action word is a call to a pre-compiler. 42 .end if.put_line('Too Many Rows returned '). when others then dbms_output. The function Exception_init() takes two parameters the first is the user defined exception name the second of the oracle engine’s exception number. -create a parent child relationship table -2292 > Entity integrity error declare e_emp_remaining EXCEPTION . begin select sal into msal from emp where deptno=20. which immediately binds the numbered exception handler to a name when encountered. This binding of a numbered of a numbered exception handler. to a name (i. exception when sal_exc then raise_application_error(-20001. PRAGMA EXCEPTION_INIT(e_emp_remaining. commit. end. exception when t_row_many then dbms_output. PRAGMA EXCEPTION_INIT(z_divide. y number:= 0 .-1476) . x number:= 20 . -----------------------------------declare t_row_many EXCEPTION .put_line('canot remove dept '). z number. Non-Predefined Exception Using PRAGMA EXCEPTION_INIT The technique that is used to bind a number exception handler to a named using Pragma Exception_init().put_line('Number is divided zero ').e.-1422) . end. exception when z_divide then dbms_output. begin delete from dept1 where deptno=10 . These lines will be included in the Declare section of the PL/SQL block.

we can identify the associated error code and error message by using two functions.100) .put_line('Too Many Rows returned '). Parameter2 (mode2) datatype2) AS|IS PL/SQL BLOCK Procedural Parameter Modes Type of Parameter Description ----------------------------IN Parameter Passes a constant value from the calling environment into the procedure.A procedure can be stored in the database. begin select sal into msal from emp where deptno=20. exception when t_row_many then dbms_output. Syntax for Creating Procedure Create (or Replace) procedure (procedure name) (Parameter1 (mode1) datatype1. which then return the message associated with the error number. . Err_msg := sunstr(SQLERRM. OUT Parameter Passes a value from the procedure to the calling environment IN OUT Parameter Passes a value from the calling environment into the procedure and a Possibly different value from the procedure back to the calling environment using the same parameter. Declare Err_num number . Begin --------Exception Err_num = SQLCODE .sal%type.-----------------------------------declare t_row_many EXCEPTION . end. End .-1422) . Err_msg Varchar2(100) . for repeated execution. PRAGMA EXCEPTION_INIT(t_row_many. We can pass an error number to SQLERRM. 43 . Error – Trapping Functions: When an Exception occurs.err_msg) . PROCEDURES A Procedure is type of subprogram that performs an action. msal emp. Insert into errors values (err_num. as a schema object. SQLCODE returns number of the Oracle error for internal exception.

steps for the printing the out parameter VARIABLE A VARCHAR2(30) VARIABLE B NUMBER VARIABLE C NUMBER EXEC QUERY_EMP (7900.1.:A.:B.3) || '-' || substr(p_phone_no. 2) create or replace procedure emp_proc (mempno in number) is begin update emp set sal=sal*2 where empno=mempno. dbms_output.comm into vname. -. end. vsal out emp.7) .ename%type. OUT Parameter create or replace procedure query_emp (vempid in emp.comm%type) IS begin select ename.4. begin c:= a+b .IN Parameter 1) create or replace procedure Add_proc (a in number. end . end . end .vcomm from emp where empno=vempid.:C) print A print B print C IN OUT Parameter create or replace procedure format_phone (p_phone_no in out varchar2) is begin p_phone_no := '(' || substr(p_phone_no.3) || ')' || substr(p_phone_no. Steps for printing the IN OUT result variable g_phone_no varchar2(15) begin :g_phone_no := '8006330575' . vname out emp.sal%type.sal.put_line('The values of c is' ||c). vcomm out emp. b in number) is c number. end.vsal. 44 .empno%type.

begin open emp_cursor . mjob emp. end loop.vsal. dbms_output. close emp_cursor . check_emp exception .sal%type . msal emp.ename%type.ename%type. vsal emp. 2) create or replace procedure emp_proc (mdeptno emp.put_line('No such Employee number exist'). EXCEPTION WHEN no_data_found then dbms_output.sal from emp where deptno=mdeptno . begin select dname into vdname from dept where deptno=mdeptno . view_proc_dept(mdeptno). loop fetch emp_cursor into vename. end . begin select ename./ ------execute format_phone(:g_phone_no) ------print g_phone_no Invoking Procedure from another procedure 1) create or replace procedure view_proc_dept (mdeptno in number) is vdname dept. vsal emp. 2) create or replace procedure view_proc_emp (mdeptno in number) is vename emp.sal%type .put_line('The employee name is' ||vename||' Salary is ' || vsal) .deptno%type ) as cursor c1 is select ename. mename emp.vsal from emp where empno=mempno. dbms_output.ename%type.sal into vename.job from emp where deptno=mdeptno.sal.put_line('The employee name is' ||vename||' Salary is ' || vsal) . cursor emp_cursor is select ename.job%type. dbms_output. exit when emp_cursor%notfound.put_line('The department name is ' ||vdname) . end . Using Exception in Procedure 1) create or replace procedure view_exec_emp (mempno in number) is vename emp. end .dname%type.sal%type . 45 .

select tax(3) from dual . parameter2 (mode2) datatype2) RETURN datatype AS|IS PL/SQL BLOCK Some Programs Using Functions 1) create or replace function tax (p_value in number) return number is Begin return (p_value * 2). end. drop procedure view_proc_dept . Functions A Function is a named PL/SQL block that returns a value. End . vlocname IN locations. else dbms_output.loc_name%type default 'unknown') IS begin insert into locations values (vlocation_id. salary is '||msal||' '||mjob) . loop fetch c1 into mename. drop procedure view_exec_emp .vloc_name).msal. 2) 46 . if c1%rowcount < 1 then raise check_emp . Dropping Procedure drop procedure view_proc_emp.begin open c1.mjob . exit when c1%notfound . exception when check_emp then dbms_output. Default Option for Parameter in Procedure create or replace procedure add_location (vlocation_id in locations. end .location_id%type default 800.put_line(' the deptno not found') . Syntax for Creating Function Create (or Replace) function (function name) (parameter1 (mode1) datatype1.put_line('the employee name is '||mename||' end if . end loop .

3) Create or replace function get_sal (mempid in emp. BEGIN select sal into v_sal from emp where empno=mempid . 47 . b number ) return number is begin return (a+b) .empno%type) return number IS v_sal number.1 -------------------select get_sal(7900) from dual .ename. end. select area (3. execution Method .2) from dual .empno%type) return number IS v_sal number. return v_sal. execution Method . Create or replace function get_sal (mempid in emp. sal. tax(sal) from emp where deptno=20 .2 -------------------Variable g_sal number execute :g_sal := get_sal(7900) Print :g_sal -------------------------------- select empno. end .create or replace function total ( a number .

--------------------------------------------------------create or replace function func_name (mempno in number) return number is msal emp. end if . else return (false) .sal%type.sal%type. if sql%rowcount > 0 then return mename . begin select ename into mename from emp where empno=mempno .ename%type . if msal > 0 then return msal . select func_name(7902) from dual . if msal > 0 then return (true) . else dbms_output. return x . begin select sal into msal from emp where empno=mempno . end if . end if . else return msal*2 . end . ---------------begin if func_name(7902) then dbms_output. ----------------------------------------------------------------------------------create or replace function func_name (mempno in number) return boolean is msal emp. begin select sal into msal from emp where empno=mempno . end. end. end if .5 . x := v_sal*.put_line('wrong') . 48 . end .x number. end . begin select sal into v_sal from emp where empno=mempid . ----------------------------------------------------------------------------------create or replace function func_name (mempno in number) return varchar2 as mename emp.put_line('right') .

Desc user_objects . Objects commonly held within a package are procedures. functions. A Package consists of two components . exceptions. return mename . Dropping a Function Drop function function_name . constants.ename%type .----------------------------------------------------------------------------------Using Exception create or replace function func_name (mempno in number) return varchar2 as mename emp. cursors and subprograms that are available for use. begin select ename into mename from emp where empno=mempno . end if .Body A Package Specification declares the types (variable of the Record type). constants. if sql%rowcount > 0 then return mename . desc user_errors select * from user_errors . 49 . end . which holds other objects within it. memory variables. exception when no_data_found then mename:='no data' . A Package body fully defines cursor. desc user_source select text from user_source where NAME='FUNC_NAME' . functions and procedure and thus implements the specification.Specification . select * from user_objects . PACKAGE and PACKAGE BODY Packages: A Package is an Oracle object. cursors and exceptions. variables.

Why Use Package Packages offer the following advantages: 1) Packages enable the organization applications into efficient modules. Procedure dept_pr (mdeptno number) . Creating the Package Body Syntax CREATE [Or Replace] PACKAGE BODY package_body_name IS | AS private type and item declarations subprogram body End package_body_name.put_line('dname is '|| mdname) . subsequent calls to related sub programs in the package require no I/O. create or replace package body emp_proc as Procedure emp_pr (mempno number) as msal number . dbms_output. Thereby reducing redundant coding. Each package is easily understood. begin select sal into msal from emp where empno=mempno . Creating the Package Specification Syntax CREATE [Or Replace] PACKAGE package_name IS | AS public type and item declarations subprogram specifications End package_name. Procedure dept_pr (mdeptno number) as mdname varchar2(10) .put_line('sal is '|| msal) . 6) Package promotes code reuse through the use of libaries that contain shared procedures and functions. end. 3) A Package's public variables and cursor persist for the duration of the session. Therefore all cursors and procedures that execute in the environment can store them. Therefore. end. 2) Package allows granting of privileges efficiently. and the interfaces between packages are simple. clear and well defined. Some Sample Program using Package and Package Body 1) create or replace package emp_proc as Procedure emp_pr (mempno number) . 4) Packages enable the overloading of procedures and functions when required. dbms_output. 5) Package improves performance by loading multiple objects into memory at once. begin select dname into mdname from dept where deptno=mdeptno. 50 . end.

emp_proc. emp_proc. END. end.put_line('the multiplication of'||x ||'and'||y||':='||z).3). declare x number . To execute this Program exec p2.f1(10). begin z:=x*y. begin x:=p2. end. procedure pro (x number. procedure proc_emp2 . 51 . return y. 2) create or replace package p2 as function f1(x number) return number .emp_pr(7369) . dbms_output.put('the dept ') . end pro. dbms_output. To execute the previous program -------------------------------declare begin dbms_output.pro(45. create or replace package body p2 as function f1(x number) return number as y number. y number) as z number.put_line(x). Using Cursors in Packages 1) create or replace package pack_cur IS cursor c1 is select empno from emp .put('the emp ') . procedure proc_emp1 . dbms_output.end. procedure pro (x number. end .dept_pr(20) . begin y:=x*(30/100).y number) . end f1.

end loop . loop fetch c1 into mempno . end proc_dept . exit when c1%rowcount >=3 . cursor c2 is select dname from dept . end .empno%type.put_line(mempno) . end loop . dbms_output. end loop .put_line(mdname) . exit when c1%rowcount >=3 . procedure proc_emp2 IS begin loop fetch c1 into mempno . exit when c1%rowcount >=6 . close c1. procedure proc_emp1 is begin open c1. dbms_output. create or replace package body pack_cur IS mempno emp. mdname dept. loop fetch c2 into mdname . create or replace package body pack_cur IS mempno number. end loop . procedure proc_dept IS begin open c2. 52 . close c2. end .put_line(mempno) . dbms_output. procedure proc_dept. dbms_output. loop fetch c1 into mempno .put_line(mempno) . end proc_emp .dname%type. end . exit when c2%rowcount >=2 . procedure proc_emp is begin open c1. procedure proc_emp . 2) create or replace package pack_cur IS cursor c1 is select empno from emp . end proc_emp1 . end proc_emp2 .end .

CREATE OR REPLACE PROCEDURE meter_to_yaard (p_meter IN number.6093. More than one procedure and function with the same name but with different parameters can be defined within a package or within a PL/SQL declaration block. begin y:=x+30. function f1(x number. kilo_2_mile CONSTANT NUMBER := 0. begin z:=x+y.Declaring a Bodiless Package CREATE or REPLACE PACKAGE global_consts IS mile_2_kilo CONSTANT NUMBER := 1. end.6214.meter_2_yard . Multiple procedures that are declared with the same name are called Overloaded Procedures. return y. end f1. yard_2_meter CONSTANT NUMBER := 0. End . Similarly. Droppimg/ Removing Package and Package Body DROP PACKAGE package_name . meter_2_yard CONSTANT NUMBER := 1. 53 . return z.0936. To Execute the Package and Package Body declare x number. OVERLOADING PROCEDURES AND FUNCTIONS A Package is an Oracle object that can hold a number of other objects like procedure and functions. multiple functions that are declared with the same name are called Overloaded Functions. create or replace package body p1 as function f1(x number) return number as y number. p_yard out Number) IS BEGIN p_yard := p_meter + global_consts. 1) create or replace package p1 as function f1(x number) return number.y number) return number. function f1(x number. y number) return number as z number. end global_consts.9144. end f1. DROP PACKAGE BODY package_body_name . end.

begin z:=x+y.f1(60) then dbms_output. dbms_output. end. else return false. dbms_output. declare x boolean. end. function f1(x number. end f1. begin if p1. end if. end.f1(10). end. end if. 2) create or replace package p1 as function f1(x number) return boolean. else return false. begin x:=p1.put_line('true').y number) return boolean as z number.begin x:=p1. 54 .put_line('true'). function f1(x number. end if.put_line(x). ---------------------declare x number. create or replace package body p1 as function f1(x number) return boolean as begin if x >30 then return true. begin if p1.f1(10) then dbms_output. end if. To execute the Program declare x boolean. end f1.30). end. if z>100 then return true.y number) return boolean.put_line(x). end.f1(10.

end emp_proc.200) then dbms_output. procedure emp_proc (mempno number.put_line('false') . schema or the database.Can be either: DML Trigger . begin select ename. . msal emp.ename%type . exception when no_data_found then dbms_output.f1(10. dbms_output.declare x boolean. view. -------------------------------------------------------------create or replace package body pack_over as procedure emp_proc (mempno number) as mename emp.Executes implicitly whenever a particular event takes place.sal%type. dbms_output. . end emp_proc.ename%type . else dbms_output.sal into mename.f1(10) then dbms_output. DELETE 55 .put_line('No data found') .mdeptno number) as mename emp.put_line('true'). procedure emp_proc (mempno number. begin select ename into mename from emp where empno=mempno .fires whenever INSERT.put_line('Employee name is '||mename||' salary is '||msal) . --------------------------------------------------------------------------------------------------------create or replace package pack_over as procedure emp_proc (mempno number) .put_line('true'). and Trigger A Trigger: . mdeptno number) .put_line('No data found') . end . end if .put_line('Employee name is '||mename) . begin if p1. end .Is a PL/SQL block or a PL/SQL procedure associated with a table. end if. end. begin if p1. exception when no_data_found then dbms_output. declare x boolean. end. UPDATE.msal from emp where empno=mempno deptno=mdeptno .

put_line('before') . Triggering user events: The triggering event is an Insert. end . shutdown or startup) occurs on a schema or a database Creating DML Triggers A triggering statement contains: . Trigger type Statements: The trigger body executes once for the triggering events. View . This is used for views that are not otherwise modifiable. INSTEAD OF: Execute the trigger body instead of the triggering statement.Schema Trigger – CREATE. ALTER.-----> BEFORE row trigger 7902 SMITH 20 7876 JONES 10 -----> AFTER row trigger 7878 SURESH 30 ----> AFTER statement trigger Syntax for creating DML Statement Triggers CREATE [OR REPLACE] trigger Trigger_name timing events1 [OR events2 OR events3 ] ON table_name Trigger_body -----------------------------------------------------------------------create or replace trigger emp_Bef_inst before insert on emp begin dbms_output.-----. AFTER .Trigger Type: Row or Statement . even if no rows are affected at all.WHEN Clause: Restricting condition .for table: BEFORE.fires whenever system events (such as Logon. Update & Delete statement on a table. A row trigger is not executed if the triggering events affect no rows. This is the default.for View: INSERT.Trigger Timing . Firing Sequence -------------------> BEFORE statement trigger Empno Ename Deptno ----.Triggering Event: On table. A statement trigger fires once. DROP DatabaseTrigger . AFTER: Execute the trigger body after the triggering DML event on a table.Trigger body: PL/SQL block DML Trigger Components BEFORE: Execute the trigger body before the triggering DML event on a table. UPDATE or DELETE .-----. Row: The trigger body executes once for each row affected by the triggering events. ------------------------------------------------------------------------ 56 .

-----------------------------------------create or replace trigger aft_ins after insert on emp for each row declare meno emp. insert into emp1 (empno.put_line('welcome'). update emp1 set sal=3333 where empno=7900 . delete from emp1 where empno=7900 .'Employee cannot update').40) . dbms_output. end.sal < 0) THEN 57 . -----------------------------------------------------------------------create or replace trigger res_salary before update of sal on emp1 begin RAISE_APPLICATION_ERROR (-20202. end. --------------------------------------------create or replace trigger res_salary before insert on emp begin dbms_output.create or replace trigger emp_aft_inst after insert on emp begin dbms_output. -----------------------------------------------------------------------CREATE TRIGGER SalaryCheck AFTER INSERT OR UPDATE OF sal ON emp1 FOR EACH ROW BEGIN IF (:new. -------------------------------------------------create or replace trigger res_salary before insert on emp1 begin RAISE_APPLICATION_ERROR (-20202. end .3333.'Employee cannot insert').put_line('New employee no is ' ||meno) . end.'Employee cannot delete').empno%type .empno . end . -----------------------------------------------------------------------create or replace trigger res_salary before delete on emp1 begin RAISE_APPLICATION_ERROR (-20202. begin meno := :new.'rrr'. end.deptno) values (3333.put_line('after') .ename.sal.

end if .'You may update into emp table only during businees').comm := :old. if a between '0100' and '0200' then raise_application_error(-20202. end if. Trigger using conditional Predicates create or replace trigger secure_emp before insert or update or delete on emp1 begin if (to_char(sysdate.'HH24:MI') not between '08:00' and '18:00') then raise_application_error (-20500. end if.comm + 0.'You may insert into emp table only during businees').comm is null then :new.comm := 0 . end if .'HHMM') into a from dual .'You may deleting emp table only during businees'). end.'You may updating emp table only during businees').'SUN')) or (to_char(sysdate. 'no negative salary allowed').RAISE_APPLICATION_ERROR(-20000.job='MANAGER') begin if inserting then :new. 58 . -----------------------------------------------------------------------create or replace trigger lunch before insert or update or delete on emp declare a varchar2(4). end. else :new. elsif updating ('SAL') then raise_application_error (-20500. else raise_application_error (-20500.05 . END. END IF.'DY') in ('SAT'. end.'SUN')) or (to_char(sysdate. end if . Restricting a ROW triggers create or replace trigger derive_comm_pct after insert or update or delete on emp1 for each row WHEN (new.'You may insert into emp table only during businees'). ---------------------------------------------------------------------------------------------create or replace trigger secure_emp before insert on emp1 begin if (to_char(sysdate. begin select to_char(sysdate.'HH24:MI') not between '08:00'and '18:00') then if deleting then raise_application_error (-20500. elsif :old. elsif inserting then raise_application_error (-20500. end .'U canot do ant DML operation during lunch time') .'DY') in ('SAT'.comm := 0 .

ename.2)).NEW_TITLE.ename.OLD_SALARY. OLD_LAST_NAME VARCHAR2(30). :old.ename. OLD_SALARY NUMBER(9.job. end. These triggers are called INSTEAD OF triggers.OLD_LAST_NAME.2) NEW_SALARY NUMBER(9. insert into emp1 (empno.sal. :new.Trigger (ROW LEVEL)(Using :old qualifier) create or replace trigger restrict_salary before insert or update of sal on emp1 for each row begin if not (:new. :old.sal.sal > 15400 then raise_application_error(-20202.hiredate. Trigger (ROW LEVEL)(Using :old and :new qulaifier) create table audit_emp_table (USERNAME VARCHAR2(30). Trigger (ROW LEVEL) (Using as Instead of Trigger) INSTEAD OF Triggers Use INSTEAD OF Triggers to modify data in which the DML statement has been issued against an inherently non-updateable view. ID VARCHAR2(20). Syntax for Creating an INSTEAD of Trigger ----------------------------------------CREATE [OR REPLACE] TRIGGER trigger_name INSTEAD OF events [or event2 or event3] ON view_name [Referencing ---------------------------------------------create table new_emp as select empno. NEW_LAST_NAME VARCHAR2(30).job.TIMESTAMP.OLD_TITLE. :old.sal.'MANAGER'.job.empno.'Employee cannot earn this amount') . ------------------------------------------create or replace trigger audit_emp_values after insert or update or delete on emp1 for each row begin insert into AUDIT_EMP_TABLE (USERNAME. end if .NEW_SALARY) values (user.ID. :old. NEW_TITLE VARCHAR2(20).2456. :new. TIMESTAMP DATE.'dddd'.'CLERK')) and :new.ename. OLD_TITLE VARCHAR2(20). :new. NEW_LAST_NAME.sal).job in ('MANAGER'.30) .deptno. select * from audit_emp_table . 59 .deptno) values (3456.job from emp . end. sysdate.

dname) .deptno .deptno from emp .deptno. update new_depts set tot_dept_sal = tot_dept_sal .sal .deptno . update new_depts set tot_dept_sal = tot_dept_sal + :new.loc from emp e. -------------------------------------------------------------------------------------------MANAGING TRIGGERS Alter trigger trigger_name Disable | enable . create view emp_dept_view as select e.dname . Alter table table_name Disable|ename ALL triggers .empno .job) .e.ename.:old. end.ename.empno.:old. update new_depts set tot_dept_sal = tot_dept_sal .sal where deptno = :new.'ACCOUNTING') .sal where deptno = :old. insert into EMP_DETAILS values (1000.:new. insert into emp_dept_view values (2345.sal where deptno = :new.deptno=e.d.deptno group by e.deptno .deptno.e. create table new_dept as select deptno.:new. sum(d. Drop trigger trigger_name .deptno. insert into new_dept values (:new. elsif deleting then delete from new_emps where empno= :old.d.sal where deptno = :new.empno. 2) create table NEW_EMP as select empno.dname from dept .'ffff') . dept e where d.deptno .dept d where e. dept d where d. elsif updating ('sal') then update new_emps set sal = :new. update new_depts set tot_dept_sal = tot_dept_sal + :new.deptno.ename. create view emp_details as select e. end if .:new.e.:new.:old.dname.deptno .job.deptno.sysdate.'dddd'. create or replace trigger ins_trigs instead of insert on emp_dept_view begin insert into new_emp values (:new.e.ename. values ( update new_depts set tot_dept_sal = tot_dept_sal + :new.:new.empno.d.deptno.e.:new.deptno where empno = :old.e.e.'suresh'.deptno .'MANAGER'.:new.ename.deptno=d.3456.deptno=e.sal) tot_dept_sal from emp d. elsif updating ('deptno') then update new_emps set deptno = :new.empno .dname from emp e . create or replace trigger new_emp_det instead of insert or update or delete on emp_details for each row begin if inserting then insert into new_emps :new.sal.deptno . 60 .sal.dname.empno.e.empno.30.20.sal where empno = :new.sal where deptno = :new. end .create table new_depts as select e.Deptno) .

LOG_DATE. create or replace trigger logoff_trigs before LOGOFF ON SCHEMA BEGIN INSERT INTO LOG_TRIG_TABLE (USER_ID.A specific error (or any error) being raised. ACTION) VALUES (user. end.CREATE. end. ALTER or DROP .sysdate.Shutting down or starting up the database .Creating Database Triggers Triggering user Events: . Creating Trigger on DDL Statements These Trigger will be fired implicitely whenever user performs any DDL operations like create.’U cannot create a table’) end. create or replace trigger logon_trigs AFTER LOGON ON SCHEMA BEGIN INSERT INTO LOG_TRIG_TABLE (USER_ID. alter or dropping an object The Syntax is : Create or replace trigger <triggername) Before|after DDL statement on schema PL/SQL Block Example Before create Create or replace trigger ddl_trigger Before create on schema begin Raise_application_error(-20222.LOG_DATE. LOG_DATE date.’dd/mm/yyyy hh24:mi:ss’) . ACTION varchar2(20)) . (user||’ has created an object at’|| LOGON and LOGOFF Trigger Example create table LOG_TRIG_TABLE ( USER_ID varchar2(10). ACTION) 61 . After create Create or replace trigger ddl_trigger after create on schema begin insert into audit_objects_use values to_char(sysdate.Logging on or off Triggering database or system event: .'Logging On') .

begin vfile_id := utl_file.2) .fclose(vfile_id) . end .It do validation also FOPEN FCLOSE GET_LINE NEW_LINE PUT Datatype = File_type create or replace procedure proc_a as vfile_id utl_file. vname varchar2(10). triggering_event.name) values (vcode. vstring varchar2(100). create or replace procedure proc_a as vfile_id utl_file.txt'.file_type.VALUES (user.file_type.vname) . vcode := substr(vstring. Viewing Trigger Information You can view the following trigger inormation by using USER_TRIGGERS SQL> select trigger_name. vcode varchar2(10). begin vfile_id := utl_file. Referencing_names.'W') . table_name.name) values (vcode. insert into person (code.'Logging Off') .1. vname := substr(vstring.fopen('C:\'. end.2) .vstring). File Input/Output (I/O) (UTL_FILE) .get_line (vfile_id. 62 .to create flat file . status. loop utl_file. vstring varchar2(100). vcode varchar2(10). commit .fopen('C:\'. insert into person (code.get_line (vfile_id. loop utl_file.It is a DB Package .sysdate. trigger_body from USER_TRIGGERS Where trigger_name='CHECK_SALARY’.2) . 'flat. exception when no_data_found then utl_file. select * from LOG_TRIG_TABLE .2) .1. trigger_type.vname) .txt'. vname varchar2(10). vcode := substr(vstring.'W') .to load data into Oracle DB from flat file .1.1. end loop . vname := substr(vstring.Used for .vstring). 'flat.

checks the statements’s syntax and associates it with the opned cursor (DDL statement are immediately executed when parsed) Binds the given value to the variable identified by its name in the parsed statement in the given cursor Executes the SQL statement and returns the number of rows processed Retrives a row for the specified cursor (for multiple rows.Enables data-defination.native) . Using Native Dynamic SQL . DBMS_SQL. end . 63 .Enables general-purpose code to be written .commit . . DBMS_SQL. end loop . Using the DBMS_SQL Package The DBMS_SQL package is used to write dynamic SQL in stored procedures and to parse DDL statements. Some of the procedures and functions of the package includes: OPEN_CURSOR PARSE BIND_VARIABLE EXECUTE FETCH_ROWS CLOSE_CURSOR Componets of the DBMS_SQL Package Function or Porcedure OPEN_CURSOR PARSE BIND_VARIABLE EXECUTE FETCH_ROWS CLOSE_CURSOR Description Opnes a new cursor and assigns a cursor ID number Parses the DDL or DML ststements: that is.open_cursor .PARSE(cursor_name. data_control or session-control statements to be written and executed from PL/SQL.dbms_sql. Oracle Supplied Packages Oracle Supplied Package Are provided with the Oracle Server Extend the functionality of the database Enables access to certain SQL features normally restricted for PL/SQL. p_rows_del out number) is cursor_name integer. call in a loop) Closes the specified cursor create or replace procedure delete_all_rows (p_tab_name in varchar2. begin cursor_name := DBMS_SQL.Is a SQL statement that contains variables that can change during runtime . p_rows_del := DBMS_sql.fclose(vfile_id) .close_cursor(cursor_name) .'DELETE From '||P_tab_name.Is written using either DBMS_SQL or native dynamic SQL.EXECUTE(cursor_name) .Is a SQL staement with placeholders abd is stored as a character string. exception when no_data_found then utl_file. .

End . . Dynamic SQL Using EXECUTE IMMEDIATE Create procedure del_rows (p_table_name in varchar2. P_rows_deld := SQL%ROWCOUNT . for n>=3 is equivalent to: CASE WHEN expr1 IS NOT NULL THEN expr1 ELSE COALESCE (expr2.. in a value in the Gregorian calendar of datatype DATE... . 64 .end..COALESCE(0. p_rows_deld out number) IS Begin Execute immediate ‘delete from ‘||p_table_name . expr2. expr2) is equivalent to: CASE WHEN IS expr1 NOT NULL THEN expr1 ELSE expr2 END Similarly.. exprn) END select comm.5) from emp . For example. :a) SQL> print a Using DBMS_JOB for Scheduling DBMS_JOB enables the scheduling and execution of PL/SQL programs: Submitting jobs Executing jobs Changing execution parameters of jobs Remove jobs Suspending Jobs New SQL function in Oracle 9i COALESCE You can also use COALESCE as a variety of the CASE expression.9*comm. comm. exprn). COALESCE (expr1.. SQL> variable a number SQL> execute del_rows ('EMP1'. COALESCE (expr1. CURRENT_DATE Purpose CURRENT_DATE returns the current date in the session time zone.

CURRENT_TIMESTAMP FROM DUAL.917550 PM -05:00 ALTER SESSION SET TIME_ZONE = '-8:0'.--------------------05:00 29-MAY-2000 13:14:03 ALTER SESSION SET TIME_ZONE = '-8:0'. CURRENT_DATE FROM DUAL. If you omit precision. precision specifies the fractional second precision of the time value returned. in a value of datatype TIMESTAMP WITH TIME ZONE. The time zone offset reflects the current local time of the SQL session. 65 . SESSIONTIMEZONE CURRENT_TIMESTAMP --------------. then the default is 6. CURRENT_DATE FROM DUAL. CURRENT_TIMESTAMP FROM DUAL. In the optional argument. SELECT SESSIONTIMEZONE.366065 AM -08:00 If you use the CURRENT_TIMESTAMP with a format mask. SELECT SESSIONTIMEZONE. SELECT SESSIONTIMEZONE. take care that the format mask matches the value returned by the function.Examples The following example illustrates that CURRENT_DATE is sensitive to the session time zone: ALTER SESSION SET TIME_ZONE = '-5:0'.18.---------------------------------------------------05:00 04-APR-00 01.21. SELECT SESSIONTIMEZONE. For example. SESSIONTIMEZONE CURRENT_TIMESTAMP --------------.--------------------08:00 29-MAY-2000 10:14:33 CURRENT_TIMESTAMP Purpose CURRENT_TIMESTAMP returns the current date and time in the session time zone. ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS'. ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS'.----------------------------------------------------08:00 04-APR-00 10. The difference between this function and LOCALTIMESTAMP is that CURRENT_TIMESTAMP returns a TIMESTAMP WITH TIME ZONE value while LOCALTIMESTAMP returns a TIMESTAMP value. consider the following table: CREATE TABLE current_test (col1 TIMESTAMP WITH TIME ZONE).17.56. SESSIONTIMEZONE CURRENT_DATE --------------. Examples The following example illustrates that CURRENT_TIMESTAMP is sensitive to the session time zone: ALTER SESSION SET TIME_ZONE = '-5:0'. SESSIONTIMEZONE CURRENT_DATE --------------.

MI. EXTRACT(YEARFROMDATE'1998-03-07') --------------------------------1998 The following example selects from the sample table hr.SSXFF PM TZH:TZM')). EXTRACT (DATETIME) Purpose EXTRACT extracts and returns the value of a specified datetime field from a datetime or interval value expression.--------suresh 2345 02-JAN-76 SMITH 7369 17-DEC-80 ALLEN 7499 20-FEB-81 WARD 7521 22-FEB-81 FIRST Purpose FIRST and LAST are very similar functions. When extracting from a datetime with a time zone value. SELECT EXTRACT(YEAR FROM DATE '1998-03-07') FROM DUAL. When you extract any of the other values. ENAME EMPNO HIREDATE ---------. The function returns the same datatype as the numeric datatype of the argument.The following statement fails because the mask does not include the TIME ZONE portion of the type returned by the function: INSERT INTO current_test VALUES (TO_TIMESTAMP_TZ(CURRENT_TIMESTAMP. Both are aggregate and analytic functions that operate on a set of values from a set of rows that rank as the FIRST or LAST with respect to a given sorting specification.---------. 'DD-MON-RR HH. the value returned is a string containing the appropriate time zone name or abbreviation. This function takes as an argument any numeric datatype or any nonnumeric datatype that can be implicitly converted to a numeric datatype. the value returned is in the Gregorian calendar. If only one row ranks as FIRST or LAST. query the V$TIMEZONE_NAMES dynamic performance view. the value returned is in UTC. The following statement uses the correct format mask to match the return type of CURRENT_TIMESTAMP: INSERT INTO current_test VALUES (TO_TIMESTAMP_TZ (CURRENT_TIMESTAMP. 'DD-MON-RR')) < 1998 ORDER BY hiredate. emp WHERE EXTRACT(YEAR FROM 66 .SSXFF PM')).MI.employees all employees who were hired after 1998: SELECT ename. the aggregate operates on the set with only one element. For a listing of time zone names and their corresponding abbreviations. hiredate FROM TO_DATE(hiredate. When you extract a TIMEZONE_REGION or TIMEZONE_ABBR (abbreviation). 'DD-MON-RR HH. empno.

The NULLIF function is logically equivalent to the following CASE expression: CASE WHEN expr1 = expr 2 THEN NULL ELSE expr1 END Examples The following example selects those employees from the sample schema hr who have changed jobs since they were hired.---------. as indicated by a job_id in the job_history table different from the current job_id in the employees table: SELECT e. but the needed value is not the sort key. job_history j WHERE e.--------ADAMS ALLEN BLAKE CLARK FORD ggggg suresh Program 67 . If they are not equal. select deptno. then the function returns expr1. If the arguments are not numeric. or Oracle returns an error.---------10 1300 5000 20 800 3000 30 1500 2850 40 3456 3456 60 2345 2345 90 5657 5657 NULLIF Purpose NULLIF compares expr1 and expr2. You cannot specify the literal NULL for expr1.ename. the FIRST and LAST functions eliminate the need for self joins or views and enable better performance. implicitly converts the other argument to that datatype. MAX(sal) KEEP (DENSE_RANK LAST ORDER BY comm) "Best" from emp group by deptno . DEPTNO Worst Best ---------. then Oracle Database determines the argument with the higher numeric precedence. then the function returns null.job) "Old Job" FROM emp e.empno = j. If they are equal.job. If both arguments are numeric datatypes. min(sal) KEEP (DENSE_RANK FIRST ORDER BY comm) "Worst".When you need a value from the first or last row of a sorted group.empno ORDER BY ename. j. then they must be of the same datatype. NULLIF(e. ENAME Old Job I ---------. and returns that datatype.

objects may help in other ways.If OO code is written. Abstract Data type Abstract Data type is a datatype that consists of one or more subtypes. zip number) .Implementing Object Techniques Object Technology: • Object Technology is another step forward in the software enginnering life cycle that allows us to: . In an object table. the chance of reusing previously written code modules is increased. CREATE TYPE person_ty AS OBJECT (name vachar2(250). • Minimizing cost through reusibility Oracle provides full support for all three different implementation – Relational. if OO database objects are created the chances that these database objects will be reused in increased. Object. address address_ty) . Why Should Objects Be Used? Objects reduce complexity by giving an intuitive way of representing complex data and its relations. zip number) . city varchar2(25).Oriented Relational. CREATE TYPE person_ty AS OBJECT (name vachar2(250).Represent real thing as objects • Object Technology is a method of managing complexity so that we can develop solutions that simulate real-world problems. major object types are described.If database objects are built using standards. city varchar2(25). OBJECT TYPES Oracle supports many different types of objects. Standard adherence:. Creation of an Object CREATE TYPE address_ty AS OBJECT (Street varchar2(50). Similarly. Besides simplifying the interaction with data. then a de facto standard for application of tables is being created. the columns of the table map to the columns of an abstract datatype. Rather that being constrained to the standard Oracle data type of NUMBER. state vachar2(25). Examples of benefits that come from using OO features are: Object reuse: . CREATE TYPE address_ty AS OBJECT (Street varchar2(50). 68 . the abstract data type can more accurately describe data. DATE. ObjectRelational. address address_ty) . In the following sections. state varchar2(25). then the chances they will be used increase exponentially. and VARCHAR2.Model real Thing . An abstract data type can be used to create an Object Table. If multiple applications or tables use the same set of database objects.

called referenced objects.Person. Object views allow the development of OO features within a relational database. CREATE TABLE customer 69 .city like ‘M%’ . A nested is a collection of rows.person. CREATE TYPE address_ty AS OBJECT (Street varchar2(50). CREATE TYPE person_ty AS OBJECT (name varchar2(25).Person. are Physically separated from the objects that refer to them. zip number) .addess. Another type of object.CREATE TABLE customer (customer_id number. Updating Data using Objects UPDATE customer client SET client. the nested table as a column. object views give the benefits of relational table storage and OO structures. also known as VARRAYS. In one sense.City FROM customer client WHERE client. the array is a nested table a limited set of rows Varying Arrays. Object views Object views allow adding OO concepts on top of existing relational tables. The size of the array is limited when it is created. A row object is different from a column object.person. an abstract data type can be created based on an existing table definition.addess. each with the same data type. They are physically embedded within another object.Name Client. Varying Arrays A varying array is a set if objects. For example. person person_ty) Retrieving Data using Objects SELECT client. References are typically among the last OO features implemented when migrating a relational database to an object-relational or pure OO one.person.Address. address address_ty) . References (also known as REFs) are essentially pointers to row objects. A row object. always represents a row.City=’Chennai’ . it is an object that is treated as a column in a table. For each record within the main table. a kind of bridge between the relational and OO worlds. on the other hand. Thus. represented as a column within the main table.Person. Deleting Data using Objects DELETE from customer client where client. city varchar2(25).city=’Mumbai’ where Client. When a table is created with a varying array. An example of a column object would be a varying array.address. state varchar2(25). Nested Tables A nested table is a table within a table. it’s a way of storing a one-to-many relationship within one table. allows storing repeating attributes in tables. References Nested tables and Varying Arrays are embedded objects.city=’Mumbai’ .Address.

If with ROWID is not specified with the REF clause. A REF can also be used in a manner similar to a foreign key in a RDBMS. potentially saving storage space.address_ty(Street. this can be used as a part of the creation of either a table or an abstract datatype Create table company_info (company_name varchar2(50). which can hold a maximum of 3 elements of data type varchar2(1000). REF columns can be added to nested tables with the ALTER TABLE command. but takes more space. Varying arrays are collectors that allow repetition of only those column values that change.zip)) from customer . the default is to not store ROWIDs with the REF values. An OID is a 128 bytes base –64 number. much the same way as a primarykey/foreign-key relationship in relational tables. an address table. if more than one table is needed in a primary-key/foreign-key relationship related to a single table. To get the value stored in the 70 . this SQL statement creates a table called company_info. The use of REFs eliminates this problem.person_ty(name. REF’s establish relationship between two-object tables.e. which contains an embedded object called address that is a varray of type company_address_ty. A call to a REF returns the OID of the object instance. as they will not allow REF values unless the corresponding entries in the SCOPE table is present. person person_ty) . and to allow the user to select that object. A REF is used primarily to store an object identifier. address company_address_ty). have difficulty. SCOPE clauses prevent dangling references. There can be only one REF clause for a given REF column. VARIABLE ARRAYS A varying array allows the storing of repeated attributes of a record in a single row. i. Now that the varying array company_address_ty is created. CREATE TYPE COMPANY_ADDRESS_TY AS VARRAY (3) OF varchar2 (1000). ORCLE stores the varying array data internally using the RAW datatype. Varying arrays can be used to accurately represent one –to –many relationships where the maximum number of elements on the many side of the relationship is known and where the order of these elements is important. each storing address information for the company. create view cust_obj of address_ty with object oid (customer_id) as select customer_id.state.(customer_id number. This data type acts as a pointer to an object. Storing a REF with a ROWID seeds dereferencing operation. because an unscoped REF can refer to any accessible object table. 3 entries per record.city. This statement creates a varray type called company_address_typ. For example. REF values can be stored with or without a ROWID. A scope clause in a definition forces a set of REFs for a given column to be confined to a single object table. Reference object The referencing object (REFs data type) is something that is new to ORACLE 8i. REF scope can be set at either the column or table level. Relational tables however. which is not very useful except as handle to the object instance. that stores addresses from several entities.

p. Oracle Database cannot restore a table to an earlier state across any DDL operations that change the structure of the table. Collectively these objects are called master tables (a replication term) or detail tables (a data warehousing term). FLASHBACK TABLE Purpose Use the FLASHBACK TABLE statement to restore an earlier state of a table in the event of human or application error.dmp log=filename. products p. p. and other materialized views. sales s WHERE t.dmp log=filename.prod_id GROUP BY t.amount_sold) AS sum_sales FROM times t. This reference uses "master tables" for consistency.prod_id = s. DEREF returns values in the object instance referenced by a specific REF value. SUM(s. Some advance features in Oracle 9i MATERIALIZED VIEW A materialized view is a database object that contains the results of a query. the DEREF routine is used. Also.calendar_year. views.time_id AND p.calendar_year.log owner=username Entire Database Level C:\> exp system/manager file=filename.log User Level Export C:\> exp system/manager file=filename. Oracle Utilities Export • A backup utility provided by Oracle • Writes data from an Oracle database into Oracle binary-format files • Exported data can only be read by the “Import” utility • A User must have connect or DBA privilege to export table • Exprt Modes: o Table: The names of the tables to be exported need to be specified o User: All objects belonging to the user are exported o Database: All database objects are exported • The command used is : exp Table(s) Level Export C:\> exp username/passward Tables=tablename. The databases containing the master tables are called the master databases CREATE MATERIALIZED VIEW sales_mv REFRESH FAST ON COMMIT AS SELECT t.prod_id.time_id = s.prod_id. The FROM clause of the query can name tables.log full=y Import • Is used for importing data exported using the exp command into the Oracle database 71 .dmp log=filename.instance that is referred to by a REF. The time in the past to which the table can be flashed back is dependent on the amount of undo data in the system.tablename file=filename.

txt To create multiple table in a SINGLE SQL Query Create schema authorization sss Create table a (a number) Create table b (a number).log Tables=(tablename.dmp log=filename.3 .Importing tables C:\> Imp username/passward file=filename.2 .ctrl.create a data file ex test.create a table ex create table person (code number(2).dmp log=filename.log fromuser = username touser=username Sql Loader • • This tool is used to move data from a Non-Oracle standard source into the Oracle Database Load data into multiple datafiles by Sql Loader . setp .create a control file load data ex . name varchar2(10)).sqlldr step -1 . Background Process is two types 1) Mandatory 2) Optional Mandatory are 1) Process Monitor (PMON) 72 .txt 10 MILLER 20 FORD step . name postion ( 04:10) char) step . Where SSS is the User Name Oracle Architecture In Every Oracle Server consists of an Oracle Instance and Database .4 c:\> sqlldr userid=sss/sss control=c:\ctrl.txt infile <file location of the data file> into table person (code position (01:03) char. An Oracle Instance is the combination of System Global Area(SGA) and the Background Process.tablename) Importing User C:\> Imp system/manager file=filename.

the Program Global Area (PGA) contains data (such as user’s session variables and arrays) for use only by a single process.ora) Redo Log file: It stores the changed information made by the Redolog buffer Cache by the help of Log Writer (LGWR). Control File: It Stores the crushial information about the database like ..Name of each data files . Password File: Password file is required to connect database remotely from one serever to another server.Database original creation date Parameter File: While datatabase is starting. System Global Area (SGA) The Shared System Global Area (SGA) contains user data and control information for a single Oracle Instance. . what parameter u have set in the database.Block Id –New Contents Data file: . Such as : Database Name Control File Location Whether Rollback Segmnet or Undo Management Background/User/Core Dump Location etc. -It stores the redo entries -Atleast two files is required and the size should be in KB’s.2) 3) 4) 5) System Monitor (SMON) Database Writer (DBWR) Log Writer (LGWR) Checkpoint (CKPT) Optional are 1) Oracle Parallel Query Option (OPQO) 2) Multi DBWR 3) Archiver (ARCH) 4) Recoverer (Reco) Oracle 1) 2) 3) 4) 5) Database consists mainly these files Redo Log File Control File Data File Parameter File Initialisation File (init. Its contents is not visible to other processes (unless Oracle multithreaded server (MTS) is used).One data file belongs only one Tablespace.The actual data stores in the data file. The file size should be in MBs or GBs or may be TBs. Program Global Area (PGA) When single-threaded servers are used.Location of each data files . Its contents is visible/accessible to several user applications and system processes.No of data files . first it reads from the parameter file. -It contains File Id. 73 . There must be atleast some parameter require to start.

the persistent area contains information that is valid and applicable through multiple executions of the SQL statement. Data Dictionary Cache This area saves the re-reading of data from the Dictionary Table on a hard disk referenced while parsing SQL statements. It contains information such as user account data. runtime stacks and buffers. environment and session parameters. Library Cache The Library Cache contains both shared and private SQL areas. it goes through a parse tree in the shared pool. contains library cache performance information for each type of object in the library cache. It contains session-specific information. Database Buffer Cache The data block buffer stores the most recently queried data from the database. Each private area is deallocated after the cursor to the session is closed. and so on. Oracle can service identical requests simply by retrieving them from its cached memory for reuse. So before performing a hard disk operation. the shared area contains the parse tree and execution path for SQL statements. The v$librarycache view lists performance information for each type of object in the library cache. A private SQL area is created for each transaction initiated. Its size is controlled by the variable DB_BLOCK_BUFFERS parameter. It also contains headers of PL/SQL packages and procedures that have been executed. It contains information such as segment information. datafile names. security and access privileges. which has a value calculated from the size of about 74 . and Privileges. data dictionary cache. Specifically. To improver Oracle performance. The number of private SQL areas a user session can have open at one time is limited by the value of the OPEN_CURSORS init. The runtime area contains data that is used only while the SQL statement is being executed.ora parameter.Shared SQL Pool When an SQL statement is issued by a user process. segment names. and available free storage space. This is done for efficiency -. The shared pool contains the library cache. execution plan and parse tree for SQL statements. Oracle uses a Shared SQL area to save in cache the intermediate results from SQL commands previously returned.to avoid time-consuming hard disk operations. table descriptions. Within the private SQL area of the library cache. extent locations. such as bind variables.

The V$bgprocess view lists all background processes. performs "garbage collection". Redo Log Buffer Cache The redo log buffer is used to store redo information in memory before it is flushed to the Online Redo Log Files. 75 . The v$process view displays all processes that are connected to the database. including background and user processes. User and Server Processes (Snnn) Applications and utilities access the RDBMS through a user process. disk blocks and memory blocks accessed while executing the statement.1 to 2 percent of the database. The v$sqlarea view displays the text of SQL statements in the shared SQL area. The server process parses and executes SQL statements that are submitted to it and returns the result sets back to the user process. which can be dedicated to one user process or shared by many user processes. Four background processes are mandatory -. and restarts failed processes in the database. Oracle doesn't have time to write modified database changes from the System Global Area (SGA) down to disk. Database Writer (DBWn) The Database Writer (DBWR) writes and retrieves blocks from datafiles through the buffer cache.required for startup of each Oracle instance: System Monitor (SMON) The System monitor performs automatic crash recovery on the Oracle instance in the event it fails. System Background Processes The PROCESSES parameter in init. and other information. It is also the process that reads data blocks from the data files into the database buffer cache.ora specifies the maximum number of processes accessing the database. It looks for free spaces and organizes them into contiguous areas. Large Pool Introduced with Oracle 8 to store user session global area infor and for parallel processing/recovery. It wakes itself up routinely to clean up free space in datafiles (much like a defragmenter for hard drives). plus the number of users accessing the statements. Its size is initialized according to the LOG_BUFFER (bytes) parameter. Process Monitor (PMON) The Process monitor performs recovery (such as releasing locks failed processes held on resources). The number of redo log space requests can be monitored using the v$sysstat view. It releases locks held by processes which failed before they released memory allocations. If the command shutdown abort is issued by the user. Some suggest using the DB_WRITERS parameter to define as many DBWR processes as there are physical disks used to store data files. The user process connects to a server process. PMON analyzes user processes that access the database. This space is managed by latching and writing the Least Recently Used (LRU) block to hard disk.

Log Writer (LGWR) The Log Writer writes and retrieves its blocks from datafiles through the Redo Log Buffer. The v$archive view provides information on the archived logs written by ARCn (ARCH pre Oracle8i). At a specified time.ora file is not set to TRUE. 76 . In Oracle 8i. the database will hang. User trace Database trace start-up and other commands and responses to commands to a database are stored in an Alert Log. If the database is operating in archivelog mode AND the ARCHIVE_LOG_START parameter in the init. Alert Logs Database start-ups and other commands and responses to commands to a database are stored in an Alert Log. Trace Writer (TRWR) The operating system Process ID for each running process are maintained in a trace file located in the file name specified in parameter BACKGROUND_DUMP_DEST. the DBWR_IO_SLAVES parameter defines the number of I/O slaves to improve performance. Redo log files are achived to tape or other media by the ARCH background process. that's folder /admin/INSTANCE_NAME/bdump under the ORACLE_BASE folder. This process is optionally enabled if parameter CHECKPOINT_PROCESS contains a TRUE value. Archival Process (ARCn) The full online redo logs are copied to the archived redo log files by this process. Other background system processes .. it updates all the data and control files with the new log file control number. Depending on the LOG_CHECKPOINT_INTERVAL parameter. It is a background process that monitors the number of dirty buffers that have not been written to disk. Checkpoint Process (CKPT) The checkpoint (CKPT) process frees up limited memory space and ensures instance recovery.. it also gives the DBWR a wakeup call to write dirty buffer to disk. By default.

Sign up to vote on this title
UsefulNot useful