INTRODUCTIONSQL is divided into the following
DDL -- create, alter, drop, truncate, rename CREATE TABLE SYNTAX :
Create table <table_name> (col1 datatype1, col2 datatype2 ...coln datatypen);
Ex: INSERTThis will be used to insert the records into table.We have two methods to insert.
SELECTING DATA
Syntax:
Ex:
NO NAME MARKS
--- ------ --------
1 Sudha 100
2 Saketh 200
1 Jagan 300
2 Naren 400
3 Ramesh
4 Madhu
5 Visu
6 Rattu
SQL> select no, name, marks from student;
NO NAME MARKS
--- ------ --------
1 Sudha 100
2 Saketh 200
1 Jagan 300
2 Naren 400
3 Ramesh
4 Madhu
5 Visu
6 Rattu
SQL> select no, name from student;
NO NAME
--- -------
1 Sudha
2 Saketh
1 Jagan
2 Naren
3 Ramesh
4 Madhu
5 Visu
6 Rattu
CONDITIONAL SELECTIONS AND OPERATORSWe have two clauses used in this
USING WHERE
Syntax:
USING ORDER BYThis will be used to ordering the columns data (ascending or descending).
Syntax:
Ex:
NO NAME MARKS
--- ------- ---------
1 Sudha 100
1 Jagan 300
2 Saketh 200
2 Naren 400
3 Ramesh
4 Madhu
5 Visu
6 Rattu
SQL> select * from student order by no desc;
NO NAME MARKS
--- ------- ---------
6 Rattu
5 Visu
4 Madhu
3 Ramesh
2 Saketh 200
2 Naren 400
1 Sudha 100
1 Jagan 300
USING DMLUSING UPDATEThis can be used to modify the table data.
Syntax:
Ex:
SQL> update student set marks = 500 where no = 2; SQL> update student set marks = 500, name = 'Venu' where no = 1; USING DELETEThis can be used to delete the table data temporarily.
Syntax:
Ex: SQL> delete student where no = 2; USING DDLUSING ALTERThis can be used to add or remove columns and to modify the precision of the datatype.
USING TRUNCATEThis can be used to delete the entire table data permanently.
Syntax:
Ex: USING DROPThis will be used to drop the database object;
Syntax:
Ex: USING RENAMEThis will be used to rename the database object;
Syntax:
Ex: USING TCLUSING COMMITThis will be used to save the work.Commit is of two types.
USING ROLLBACKThis will undo the operation.This will be applied in two methods.
Syntax: Rollback or rollback work; * While process is going on, if suddenly power goes then oracle will rollback the transaction.USING SAVEPOINTYou can use savepoints to rollback portions of your current set of transactions.
Syntax:
Ex:
SQL> savepoint s1;
SQL> insert into student values(1, 'a', 100);
SQL> savepoint s2;
SQL> insert into student values(2, 'b', 200);
SQL> savepoint s3;
SQL> insert into student values(3, 'c', 300);
SQL> savepoint s4;
SQL> insert into student values(4, 'd', 400);
Before rollback
SQL> select * from student;
NO NAME MARKS
--- ------- ----------
1 a 100
2 b 200
3 c 300
4 d 400
SQL> rollback to savepoint s3;
Or SQL> rollback to s3; This will rollback last two records. SQL> select * from student;
NO NAME MARKS
--- ------- ----------
1 a 100
2 b 200
USING DCLDCL commands are used to granting and revoking the permissions.USING GRANTThis is used to grant the privileges to other users.
Syntax: SQL> grant select on student to sudha; -- you can give individual privilege SQL> grant select, insert on student to sudha; -- you can give set of privileges SQL> grant all on student to sudha; -- you can give all privileges
The sudha user has to use dot method to access the object.
The sudha user can not grant permission on student table to other users. To get this type of
option use the following.
USING REVOKEThis is used to revoke the privileges from the users to which you granted the privileges.
Syntax: SQL> revoke select on student form sudha; -- you can revoke individual privilege SQL> revoke select, insert on student from sudha; -- you can revoke set of privileges SQL> revoke all on student from sudha; -- you can revoke all privilegesUSING ALIASESCREATE WITH SELECTWe can create a table using existing table [along with data].
Syntax: SQL> create table student1 as select * from student;
Creating table with your own column names.
Creating table with specified columns.
Creating table with out table data.
INSERT WITH SELECTUsing this we can insert existing table data to a another table in a single trip. But the table structure should be same.
Syntax:
Ex:
Inserting data into specified columns
COLUMN ALIASES
Syntax:
Ex: TABLE ALIASESIf you are using table aliases you can use dot method to the columns.
Syntax:
Ex: USING MERGEMERGEYou can use merge command to perform insert and update in a single command.Ex:
SQL> Merge into student1 s1
Using (select *From student2) s2
On(s1.no=s2.no)
When matched then
Update set marks = s2.marks
When not matched then
Insert (s1.no,s1.name,s1.marks)
Values(s2.no,s2.name,s2.marks);
In the above the two tables are with the same structure but we can merge different structured
tables also but the datatype of the columns should match.
Assume that student1 has columns like no,name,marks and student2 has columns like no, name, hno, city.
SQL> Merge into student1 s1
Using (select *From student2) s2
On(s1.no=s2.no)
When matched then
Update set marks = s2.hno
When not matched then
Insert (s1.no,s1.name,s1.marks)
Values(s2.no,s2.name,s2.hno);
MULTIBLE INSERTSWe have table called DEPT with the following columns and dataDEPTNO DNAME LOC -------- -------- ---- 10 accounting new york 20 research dallas 30 sales Chicago 40 operations boston
** You can use multi tables with specified fields, with duplicate rows, with conditions, with first and else clauses. FUNCTIONSFunctions can be categorized as follows.
SINGLE ROW FUNCTIONSSingle row functions can be categorized into five.These will be applied for each row and produces individual output for each row.
NUMERIC FUNCTIONS
STRING FUNCTIONS
DATE FUNCTIONS
Oracle default date format is DD-MON-YY. We can change the default format to our desired format by using the following command.
SQL> alter session set nls_date_format = 'DD-MONTH-YYYY';
MISCELLANEOUS FUNCTIONS
CONVERSION FUNCTIONS
GROUP FUNCTIONS
CONSTRAINTSConstraints are categorized as follows.
We can add constraints in three ways.
If you want to give a name to the constraint, you have to use the constraint clause. NOT NULLThis is used to avoid null values.We can add this constraint in column level only. Ex: SQL> create table student(no number(2) not null, name varchar(10), marks number(3)); SQL> create table student(no number(2) constraint nn not null, name varchar(10), marks number(3)); CHECKThis is used to insert the values based on specified condition.We can add this constraint in all three levels. Ex: COLUMN LEVELSQL> create table student(no number(2) , name varchar(10), marks number(3) check (marks > 300)); SQL> create table student(no number(2) , name varchar(10), marks number(3) constraint ch check(marks > 300)); TABLE LEVELSQL> create table student(no number(2) , name varchar(10), marks number(3), check (marks > 300)); SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint ch check(marks > 300)); ALTER LEVELSQL> alter table student add check(marks>300); SQL> alter table student add constraint ch check(marks>300); UNIQUEThis is used to avoid duplicates but it allow nulls.We can add this constraint in all three levels. Ex: COLUMN LEVELSQL> create table student(no number(2) unique, name varchar(10), marks number(3)); SQL> create table student(no number(2) constraint un unique, name varchar(10), marks number(3)); TABLE LEVELSQL> create table student(no number(2) , name varchar(10), marks number(3), unique(no)); SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint un unique(no)); ALTER LEVELSQL> alter table student add unique(no); SQL> alter table student add constraint un unique(no); PRIMARY KEYThis is used to avoid duplicates and nulls. This will work as combination of unique and not null. Primary key always attached to the parent table. We can add this constraint in all three levels.Ex: COLUMN LEVELSQL> create table student(no number(2) primary key, name varchar(10), marks number(3)); SQL> create table student(no number(2) constraint pk primary key, name varchar(10), marks number(3)); TABLE LEVELSQL> create table student(no number(2) , name varchar(10), marks number(3), primary key(no)); SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint pk primary key(no)); ALTER LEVELSQL> alter table student add primary key(no); SQL> alter table student add constraint pk primary key(no); FOREIGN KEYThis is used to reference the parent table primary key column which allows duplicates. Foreign key always attached to the child table. We can add this constraint in table and alter levels only.Ex: TABLE LEVELSQL> create table emp(empno number(2), ename varchar(10), deptno number(2), primary key(empno), foreign key(deptno) references dept(deptno)); SQL> create table emp(empno number(2), ename varchar(10), deptno number(2), constraint pk primary key(empno), constraint fk foreign key(deptno) references dept(deptno)); ALTER LEVELSQL> alter table emp add foreign key(deptno) references dept(deptno); SQL> alter table emp add constraint fk foreign key(deptno) references dept(deptno); Once the primary key and foreign key relationship has been created then you can not remove any parent record if the dependent childs exists. USING ON DELTE CASCADEBy using this clause you can remove the parent record even it childs exists. Because when ever you remove parent record oracle automatically removes all its dependent records from child table, if this clause is present while creating foreign key constraint.Ex: TABLE LEVELSQL> create table emp(empno number(2), ename varchar(10), deptno number(2), primary key(empno), foreign key(deptno) references dept(deptno) on delete cascade); SQL> create table emp(empno number(2), ename varchar(10), deptno number(2), constraint pk primary key(empno), constraint fk foreign key(deptno) references dept(deptno) on delete cascade); ALTER LEVELSQL> alter table emp add foreign key(deptno) references dept(deptno) on delete cascade; SQL> alter table emp add constraint fk foreign key(deptno) references dept(deptno) on delete cascade; COMPOSITE KEYSA composite key can be defined on a combination of columns. We can define composite keys on entity integrity and referential integrity constraints. Composite key can be defined in table and alter levels only.Ex: UNIQUE (TABLE LEVEL)SQL> create table student(no number(2) , name varchar(10), marks number(3), unique(no,name)); SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint un unique(no,name)); UNIQUE (ALTER LEVEL)SQL> alter table student add unique(no,name); SQL> alter table student add constraint un unique(no,name); PRIMARY KEY (TABLE LEVEL)SQL> create table student(no number(2) , name varchar(10), marks number(3), primary key(no,name)); SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint pk primary key(no,name)); PRIMARY KEY (ALTER LEVEL)SQL> alter table student add primary key(no,anme); SQL> alter table student add constraint pk primary key(no,name); FOREIGN KEY (TABLE LEVEL)SQL> create table emp(empno number(2), ename varchar(10), deptno number(2), dname varchar(10), primary key(empno), foreign key(deptno,dname) references dept(deptno,dname)); SQL> create table emp(empno number(2), ename varchar(10), deptno number(2), dname varchar(10), constraint pk primary key(empno), constraint fk foreign key(deptno,dname) references dept(deptno,dname)); FOREIGN KEY (ALTER LEVEL)SQL> alter table emp add foreign key(deptno,dname) references dept(deptno,dname); SQL> alter table emp add constraint fk foreign key(deptno,dname) references dept(deptno,dname); DEFERRABLE CONSTRAINTSEach constraint has two additional attributes to support deferred checking of constraints.
Deferred initially deferred checks for constraint violation at the time of commit. Ex: SQL> create table student(no number(2), name varchar(10), marks number(3), constraint un unique(no) deferred initially immediate); SQL> create table student(no number(2), name varchar(10), marks number(3), constraint un unique(no) deferred initially deferred); SQL> alter table student add constraint un unique(no) deferrable initially deferred; SQL> set constraints all immediate; This will enable all the constraints violations at the time of inserting. SQL> set constraints all deferred; This will enable all the constraints violations at the time of commit. OPERATIONS WITH CONSTRAINTSPossible operations with constraints as follows.
ENABLEThis will enable the constraint. Before enable, the constraint will check the existing data.Ex: SQL> alter table student enable constraint un; DISABLEThis will disable the constraint.Ex: SQL> alter table student enable constraint un; ENFORCEThis will enforce the constraint rather than enable for future inserts or updates.This will not check for existing data while enforcing data. Ex: SQL> alter table student enforce constraint un; DROPThis will remove the constraint.Ex: SQL> alter table student drop constraint un; Once the table is dropped, constraints automatically will drop. CASE AND DEFAULTCASECase is similar to decode but easier to understand while going through codingEx: SQL> Select sal, Case sal When 500 then 'low' When 5000 then 'high' Else 'medium' End case From emp;
SAL CASE
----- --------
500 low
2500 medium
2000 medium
3500 medium
3000 medium
5000 high
4000 medium
5000 high
1800 medium
1200 medium
2000 medium
2700 medium
2200 medium
3200 medium
DEFAULTDefault can be considered as a substitute behavior of not null constraint when applied to new rows being entered into the table.When you define a column with the default keyword followed by a value, you are actually telling the database that, on insert if a row was not assigned a value for this column, use the default value that you have specified. Default is applied only during insertion of new rows. Ex: SQL> create table student(no number(2) default 11,name varchar(2)); SQL> insert into student values(1,'a'); SQL> insert into student(name) values('b'); SQL> select * from student;
NO NAME
------ ---------
1 a
11 b
SQL> insert into student values(null, 'c'); SQL> select * from student;
NO NAME
------ ---------
1 a
11 b
C
-- Default can not override nulls.
ABSTRACT DATA TYPESSome times you may want type which holds all types of data including numbers, chars and special characters something like this. You can not achieve this using pre-defined types.You can define custom types which holds your desired data. Ex: Suppose in a table we have address column which holds hno and city information. We will define a custom type which holds both numeric as well as char data. CREATING ADTSQL> create type addr as object(hno number(3),city varchar(10)); / CREATING TABLE BASED ON ADTSQL> create table student(no number(2),name varchar(2),address addr); INSERTING DATA INTO ADT TABLESSQL> insert into student values(1,'a',addr(111,'hyd')); SQL> insert into student values(2,'b',addr(222,'bang')); SQL> insert into student values(3,'c',addr(333,'delhi')); SELECTING DATA FROM ADT TABLESSQL> select * from student;
NO NAME ADDRESS(HNO, CITY)
--- ---- --------------------
1 a ADDR(111, 'hyd')
2 b ADDR(222, 'bang')
3 c ADDR(333, 'delhi')
SQL> select no,name,s.address.hno,s.address.city from student s;
NO NAME ADDRESS.HNO ADDRESS.CITY
-- ---- --------- ------------
1 a 111 hyd
2 b 222 bang
3 c 333 delhi
UPDATE WITH ADT TABLESSQL> update student s set s.address.city = 'bombay' where s.address.hno = 333; SQL> select no,name,s.address.hno,s.address.city from student s;
NO NAME ADDRESS.HNO ADDRESS.CITY
--- ------ ------- ----------------
1 a 111 hyd
2 b 222 bang
3 c 333 bombay
DELETE WITH ADT TABLESSQL> delete student s where s.address.hno = 111; SQL> select no,name,s.address.hno,s.address.city from student s;
NO NAME ADDRESS.HNO ADDRESS.CITY
-- ---- ------------ ----------------
2 b 222 bang
3 c 333 bombay
DROPPING ADTSQL> drop type addr; OBJECT VIEWS AND METHODSOBJECT VIEWSIf you want to implement objects with the existing table, object views come into picture.You define the object and create a view which relates this object to the existing table nothing but object view. Object views are used to relate the user defined objects to the existing table. Ex:
METHODSYou can define methods which are nothing but functions in types and apply in the tables which holds the types;Ex:
VARRAYS AND NESTED TABLESVARRAYSA varying array allows you to store repeating attributes of a record in a single row but with limit.Ex:
NESTED TABLESA nested table is, as its name implies, a table within a table.In this case it is a table that is represented as a column within another table. Nested table has the same effect of varrays but has no limit. Ex:
FLASHBACK QUERYUsed to retrieve the data which has been already committed with out going for recovery. Flashbacks are of two types
Ex:
EXTERNAL TABLES
ACCESSING EXTERNAL TABLE DATA
Ex: CREATING DIRECTORY AND OS LEVEL FILESQL> SQLplus system/manager SQL> Create directory saketh_dir as '/Visdb/visdb/9.2.0/external'; SQL> Grant all on directory saketh_dir to saketh; SQL> Conn saketh/saketh SQL> Spool dept.lst SQL> Select deptno || ',' || dname || ',' || loc from dept; SQL> Spool off CREATING EXTERNAL TABLESQL> Create table dept_ext (deptno number(2), Dname varchar(14), Loc varchar(13)) Organization external ( type oracle_loader Default directory saketh_dir Access parameters ( records delimited by newline Fields terminated by "," ( deptno number(2), Dname varchar(14), Loc varchar(13))) Location ('/Visdb/visdb/9.2.0/dept.lst')); SELECTING DATA FROM EXTERNAL TABLESQL> select * from dept_ext; This will read from dept.lst which is a operating system level file. LIMITATIONS ON EXTERNAL TABLES
BENEFITS OF EXTERNAL TABLES
REF DEREF VALUEREF
DEREF
VALUE
Ex:
REF CONSTRAINTS
SQL> Create table orders (order_no number(2), vendor_info ref vendor_adt scope is vendors); Or SQL> Create table orders (order_no number(2), vendor_info ref vendor_adt constraint fk references vendors); OBJECT VIEWS WITH REFERENCES
Ex:
PARTITIONS
TYPES
ADVANTAGES
ADVANTAGES OF PARTITIONS BY STORING THEM IN DIFFERENT TABLESPACES
DISADVANTAGES
RANGE PARTITIONS
LIST PARTITIONS
HASH PARTITIONS
SUB-PARTITIONS WITH RANGE AND HASHSubpartitions clause is used by hash only.We can not create subpartitions with list and hash partitions.
DATA MODEL
GROUP BY AND HAVINGGROUP BY
Ex: SQL> select deptno, sum(sal) from emp group by deptno;
DEPTNO SUM(SAL)
---------- ----------
10 8750
20 10875
30 9400
SQL> select deptno,job,sum(sal) from emp group by deptno,job;
DEPTNO JOB SUM(SAL)
---------- --------- ----------
10 CLERK 1300
10 MANAGER 2450
10 PRESIDENT 5000
20 ANALYST 6000
20 CLERK 1900
20 MANAGER 2975
30 CLERK 950
30 MANAGER 2850
30 SALESMAN 5600
HAVINGThis will work as where clause which can be used only with group by because of absence of where clause in group by.Ex: SQL> select deptno,job,sum(sal) tsal from emp group by deptno,job having sum(sal) > 3000;
DEPTNO JOB TSAL
---------- --------- ----------
10 PRESIDENT 5000
20 ANALYST 6000
30 SALESMAN 5600
SQL> select deptno,job,sum(sal) tsal from emp group by deptno,job having sum(sal) > 3000 order by job;
DEPTNO JOB TSAL
---------- --------- ----------
20 ANALYST 6000
10 PRESIDENT 5000
30 SALESMAN 5600
ORDER OF EXECUTION
ROLLUP GROUPING CUBEThese are the enhancements to the group by feature.USING ROLLUPThis will give the salaries in each department in each job category along wih the total salary fot individual departments and the total salary of all the departments. SQL> Select deptno,job,sum(sal) from emp group by rollup(deptno,job);
DEPTNO JOB SUM(SAL)
---------- --------- ----------
10 CLERK 1300
10 MANAGER 2450
10 PRESIDENT 5000
10 8750
20 ANALYST 6000
20 CLERK 1900
20 MANAGER 2975
20 10875
30 CLERK 950
30 MANAGER 2850
30 SALESMAN 5600
30 9400
29025
USING GROUPINGIn the above query it will give the total salary of the individual departments but with a blank in the job column and gives the total salary of all the departments with blanks in deptno and job columns.To replace these blanks with your desired string grouping will be used SQL> select decode(grouping(deptno),1,'All Depts',deptno),decode(grouping(job),1,'All jobs',job),sum(sal) from emp group by rollup(deptno,job); DECODE(GROUPING(DEPTNO),1,'ALLDEPTS',DEP DECODE(GR SUM(SAL) -------------------------- ----------------------- -------------- 10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 10 All jobs 8750 20 ANALYST 6000 20 CLERK 1900 20 MANAGER 2975 20 All jobs 10875 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600 30 All jobs 9400 All Depts All jobs 29025
USING CUBEThis will give the salaries in each department in each job category, the total salary for individual departments, the total salary of all the departments and the salaries in each job category.SQL> select decode(grouping(deptno),1,'All Depts',deptno),decode(grouping(job),1,'All Jobs',job),sum(sal) from emp group by cube(deptno,job); DECODE(GROUPING(DEPTNO),1,'ALLDEPTS',DEP DECODE(GR SUM(SAL) ------------------------- ------------------------ ------------ 10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 10 All Jobs 8750 20 ANALYST 6000 20 CLERK 1900 20 MANAGER 2975 20 All Jobs 10875 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600 30 All Jobs 9400 All Depts ANALYST 6000 All Depts CLERK 4150 All Depts MANAGER 8275 All Depts PRESIDENT 5000 All Depts SALESMAN 5600 All Depts All Jobs 29025 SET OPERATORSTYPES
UNIONThis will combine the records of multiple tables having the same structure.Ex: SQL> select * from student1 union select * from student2; UNION ALLThis will combine the records of multiple tables having the same structure but including duplicates.Ex: SQL> select * from student1 union all select * from student2; INTERSECTThis will give the common records of multiple tables having the same structure.Ex: SQL> select * from student1 intersect select * from student2; MINUSThis will give the records of a table whose records are not in other tables having the same structure.Ex: SQL> select * from student1 minus select * from student2; VIEWS
TYPES
WHY VIEWS?
VIEWS WITHOUT DML
Ex: SQL> Create view dept_v as select *from dept with read only; SQL> Create view dept_v as select deptno, sum(sal) t_sal from emp group by deptno; SQL> Create view stud as select rownum no, name, marks from student; SQL> Create view student as select *from student1 union select *from student2; SQL> Create view stud as select distinct no,name from student; VIEWS WITH DML
CREATING VIEW WITHOUT HAVING THE BASE TABLESQL> Create force view stud as select *From student; -- Once the base table was created then the view is validated. VIEW WITH CHECK OPTION CONSTRAINTSQL> Create view stud as select *from student where marks = 500 with check option constraint Ck; - Insert possible with marks value as 500 - Update possible excluding marks column - Delete possible DROPPING VIEWSSQL> drop view dept_v; SYNONYM AND SEQUENCESYNONYMA synonym is a database object, which is used as an alias for a table, view or sequence.TYPES
ADVANTAGES
CREATE AND DROPSQL> create synonym s1 for emp; SQL> create public synonym s2 for emp; SQL> drop synonym s1; SEQUENCE
Syntax: Create sequence <seq_name> [increment bty n] [start with n] [maxvalue n] [minvalue n] [cycle/nocycle] [cache/nocache];
By defalult the sequence starts with 1, increments by 1 with minvalue of 1 and with nocycle, nocache. Cache option pre-alloocates a set of sequence numbers and retains them in memory for faster access. Ex: SQL> create sequence s; SQL> create sequence s increment by 10 start with 100 minvalue 5 maxvalue 200 cycle cache 20; USING SEQUENCESQL> create table student(no number(2),name varchar(10)); SQL> insert into student values(s.nextval, 'saketh');
CREATING ALPHA-NUMERIC SEQUENCESQL> create sequence s start with 111234; SQL> Insert into student values (s.nextval || translate (s.nextval,'1234567890','abcdefghij')); ALTERING SEQUENCEWe can alter the sequence to perform the following.
Ex: SQL> alter sequence s minvalue 5; SQL> alter sequence s increment by 2; SQL> alter sequence s cache 10; DROPPING SEQUENCESQL> drop sequence s; JOINS
TYPES
SQL> select * from dept;
DEPTNO DNAME LOC
------ ---------- ----------
10 mkt hyd
20 fin bang
30 hr bombay
SQL> select * from emp;
EMPNO ENAME JOB MGR DEPTNO
------ ---------- ---------- ---------- ----------
111 saketh analyst 444 10
222 sudha clerk 333 20
333 jagan manager 111 10
444 madhu engineer 222 40
EQUI JOINA join which contains an '=' operator in the joins condition.Ex: SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno=d.deptno;
EMPNO ENAME JOB DNAME LOC
------ --------- ------- ---------- ----------
111 saketh analyst mkt hyd
333 jagan manager mkt hyd
222 sudha clerk fin bang
USING CLAUSESQL> select empno,ename,job ,dname,loc from emp e join dept d using(deptno);
EMPNO ENAME JOB DNAME LOC
------- ---------- -------- ---------- ----------
111 saketh analyst mkt hyd
333 jagan manager mkt hyd
222 sudha clerk fin bang
ON CLAUSESQL> select empno,ename,job,dname,loc from emp e join dept d on(e.deptno=d.deptno);
EMPNO ENAME JOB DNAME LOC
------ ---------- -------- ---------- -------
111 saketh analyst mkt hyd
333 jagan manager mkt hyd
222 sudha clerk fin bang
NON-EQUI JOINA join which contains an operator other than '=' in the joins condition.Ex: SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno > d.deptno;
EMPNO ENAME JOB DNAME LOC
------- ---------- ---------- ---------- ----------
222 sudha clerk mkt hyd
444 madhu engineer mkt hyd
444 madhu engineer fin bang
444 madhu engineer hr bombay
SELF JOINJoining the table itself is called self join.Ex: SQL> select e1.empno,e2.ename,e1.job,e2.deptno from emp e1,emp e2 where e1.empno=e2.mgr;
EMPNO ENAME JOB DEPTNO
------ -------- ------- --------
111 jagan analyst 10
222 madhu clerk 40
333 sudha manager 20
444 saketh engineer 10
NATURAL JOINNatural join compares all the common columns.Ex: SQL> select empno,ename,job,dname,loc from emp natural join dept;
EMPNO ENAME JOB DNAME LOC
---------- ---------- ---------- ------ --------
111 saketh analyst mkt hyd
333 jagan manager mkt hyd
222 sudha clerk fin bang
CROSS JOINThis will gives the cross product.Ex: SQL> select empno,ename,job,dname,loc from emp cross join dept;
EMPNO ENAME JOB DNAME LOC
------- ------- ---------- ------- ------
111 saketh analyst mkt hyd
222 sudha clerk mkt hyd
333 jagan manager mkt hyd
444 madhu engineer mkt hyd
111 saketh analyst fin bang
222 sudha clerk fin bang
333 jagan manager fin bang
444 madhu engineer fin bang
111 saketh analyst hr bombay
222 sudha clerk hr bombay
333 jagan manager hr bombay
444 madhu engineer hr bombay
OUTER JOINOuter join gives the non-matching records along with matching records.LEFT OUTER JOINThis will display the all matching records and the records which are in left hand side table those that are not in right hand side table.Ex: SQL> select empno,ename,job,dname,loc from emp e left outer join dept d on(e.deptno=d.deptno); Or SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno=d.deptno(+);
EMPNO ENAME JOB DNAME LOC
-------- -------- -------- -------- ------
111 saketh analyst mkt hyd
333 jagan manager mkt hyd
222 sudha clerk fin bang
444 madhu engineer
RIGHT OUTER JOINThis will display the all matching records and the records which are in right hand side table those that are not in left hand side table.Ex: SQL> select empno,ename,job,dname,loc from emp e right outer join dept d on(e.deptno=d.deptno); Or SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno(+) = d.deptno;
EMPNO ENAME JOB DNAME LOC
------- -------- ---------- ---------- ----------
111 saketh analyst mkt hyd
333 jagan manager mkt hyd
222 sudha clerk fin bang
hr bombay
FULL OUTER JOINThis will display the all matching records and the non-matching records from both tables.Ex: SQL> select empno,ename,job,dname,loc from emp e full outer join dept d on(e.deptno=d.deptno);
EMPNO ENAME JOB DNAME LOC
------ ------- ---------- ---------- ----------
333 jagan manager mkt hyd
111 saketh analyst mkt hyd
222 sudha clerk fin bang
444 madhu engineer
hr bombay
INNER JOINThis will display all the records that have matched.Ex: SQL> select empno,ename,job,dname,loc from emp inner join dept using(deptno);
EMPNO ENAME JOB DNAME LOC
------ -------- -------- -------- --------
111 saketh analyst mkt hyd
333 jagan manager mkt hyd
222 sudha clerk fin bang
SUBQUERIES AND EXISTSSUBQUERIES
TYPES
SINGLE ROW SUBQUERIESIn single row subquery, it will return one value.Ex: SQL> select * from emp where sal > (select sal from emp where empno = 7566);
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ------ --------- ------- ---------- ----- ------ --------
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20
MULTI ROW SUBQUERIES
Ex: SQL> select * from emp where sal > any (select sal from emp where sal between 2500 and 4000);
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
------ ------- ------- ------ ---------- ------ ------ ---------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20
SQL> select * from emp where sal > all (select sal from emp where sal between 2500 and 4000);
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
------ ------- --------- ----- ---------- ------ ----- -------
7839 KING PRESIDENT 17-NOV-81 5000 10
MULTIPLE SUBQUERIES
Ex: SQL> select * from emp where sal = (select max(sal) from emp where sal < (select max(sal) from emp));
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ------ -------- ---------- --------- ----- ----- -------
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
CORRELATED SUBQUERIESA subquery is evaluated once for the entire parent statement where as a correlated subquery is evaluated once for every row processed by the parent statement.Ex: SQL> select distinct deptno from emp e where 5 <= (select count(ename) from emp where e.deptno = deptno);
DEPTNO
--------
20
30
EXISTSExists function is a test for existence. This is a logical test for the return of rows from a query.Ex: Suppose we want to display the department numbers which has more than 4 employees. SQL> select deptno,count(*) from emp group by deptno having count(*) > 4;
DEPTNO COUNT(*)
--------- ----------
20 5
30 6
From the above query can you want to display the names of employees ?
SQL> select deptno,ename, count(*) from emp group by deptno,ename having count(*) > 4;
no rows selected
The above query returns nothing because combination of deptno and ename never return more than one count. The solution is to use exists which follows.SQL> select deptno,ename from emp e1 where exists (select * from emp e2 where e1.deptno=e2.deptno group by e2.deptno having count(e2.ename) > 4) order by deptno,ename;
DEPTNO ENAME
--------- ----------
20 ADAMS
20 FORD
20 JONES
20 SCOTT
20 SMITH
30 ALLEN
30 BLAKE
30 JAMES
30 MARTIN
30 TURNER
30 WARD
NOT EXISTSSQL> select deptno,ename from emp e1 where not exists (select * from emp e2 where e1.deptno=e2.deptno group by e2.deptno having count(e2.ename) > 4) order by deptno,ename;
DEPTNO ENAME
--------- ----------
10 CLARK
10 KING
10 MILLER
WALKUP TREES AND INLINE VIEWWALKUP TREESUsing hierarchical queries, you can retrieve data based on a natural hierarchical relationship between rows in a table. However, where a hierarchical relationship exists between the rows of a table, a process called tree walking enables the hierarchy to be constructed.Ex: SQL> select ename || '==>' || prior ename, level from emp start with ename = 'KING' connect by prior empno=mgr; ENAME||'==>'||PRIORENAM LEVEL ------------------------ -------- KING==> 1 JONES==>KING 2 SCOTT==>JONES 3 ADAMS==>SCOTT 4 FORD==>JONES 3 SMITH==>FORD 4 BLAKE==>KING 2 ALLEN==>BLAKE 3 WARD==>BLAKE 3 MARTIN==>BLAKE 3 TURNER==>BLAKE 3 JAMES==>BLAKE 3 CLARK==>KING 2 MILLER==>CLARK 3
INLINE VIEW OR TOP-N ANALYSISIn the select statement instead of table name, replacing the select statement is known as inline view.Ex: SQL> Select ename, sal, rownum rank from (select *from emp order by sal); ENAME SAL RANK ------- ---------- ------- SMITH 800 1 JAMES 950 2 ADAMS 1100 3 WARD 1250 4 MARTIN 1250 5 MILLER 1300 6 TURNER 1500 7 ALLEN 1600 8 CLARK 2450 9 BLAKE 2850 10 JONES 2975 11 SCOTT 3000 12 FORD 3000 13 KING 5000 14 LOCKS
TYPES
ROW LEVEL LOCKS
SQL> select * from emp where sal > 3000 for update of comm.; TABLE LEVEL LOCKSA table level lock will protect table data thereby guaranteeing data integrity when data is being accessed concurrently by multiple users.A table lock can be held in several modes.
SHARE LOCK
SQL> lock table emp in share mode; SHARE UPDATE LOCK
SQL> lock table emp in share update mode; EXCLUSIVE LOCK
SQL> lock table emp in share exclusive mode; NOWAIT
SQL> lock table emp in exclusive mode nowait. DEADLOCK
INDEXES
WHY INDEXES?Indexes are most useful on larger tables, on columns that are likely to appear in where clauses as simple equality.TYPES
UNIQUE INDEX
Ex: SQL> create unique index stud_ind on student(sno); NON-UNIQUE INDEXNon-Unique indexes do not impose the above restriction on the column values.Ex: SQL> create index stud_ind on student(sno); BTREE INDEX or ASCENDING INDEX
Ex: SQL> create index stud_ind on student(sno); BITMAP INDEXThis can be used for low cardinality columns: that is columns in which the number of distinct values is snall when compared to the number of the rows in the table.Ex: SQL> create bitmap index stud_ind on student(sex); COMPOSITE INDEX
Ex: SQL> create bitmap index stud_ind on student(sno, sname); REVERSE KEY INDEX
Ex: SQL> create index stud_ind on student(sno, reverse); We can rebuild a reverse key index into normal index using the noreverse keyword. Ex: SQL> alter index stud_ind rebuild noreverse; FUNCTION BASED INDEXThis will use result of the function as key instead of using column as the value for the key.Ex: SQL> create index stud_ind on student(upper(sname)); DESCENDING INDEX
Ex: SQL> create index stud_ind on student(sno desc); TEXT INDEX
TYPESThere are several different types of indexes available in oracle 9i.The first, CONTEXT is supported in oracle 8i as well as oracle 9i. As of oracle 9i, you can use the CTXCAT text index fo further enhance your text index management and query capabilities.
With CONTEXT indexes, you need to manually tell oracle to update the values in the text index after data changes in base table. CTXCAT index types do not generate score values during the text queries. HOW TO CREATE TEXT INDEX ?
Ex: Suppose you have a table called BOOKS with the following columns Title, Author, Info. SQL> create index book_index on books(info) indextype is ctxsys.context; SQL> create index book_index on books(info) indextype is ctxsys.ctxcat; TEXT QUERIESOnce a text index is created on the info column of BOOKS table, text-searching capabilities increase dynamically.CONTAINS & CATSEARCHCONTAINS function takes two parameters - the column name and the search string.Syntax: Contains(indexed_column, search_str); If you create a CTXCAT index, use the CATSEARCH function in place of CONTAINS. CATSEARCH takes three parameters - the column name, the search string and the index set. Syntax: Contains(indexed_column, search_str, index_set); HOW A TEXT QEURY WORKS ?
SQL> select * from books where contains(info, 'property') > 0; SQL> select * from books where catsearch(info, 'property', null) > 0; Suppose if you want to know the score of the 'property' in each book, if score values for individual searches range from 0 to 10 for each occurrence of the string within the text then use the score function. SQL> select title, score(10) from books where contains(info, 'property', 10) > 0; SEARCHING FOR AN EXACT MATCH OF MULTIPLE WORDSThe following queries will search for two words.SQL> select * from books where contains(info, 'property AND harvests') > 0; SQL> select * from books where catsearch(info, 'property AND harvests', null) > 0; Instead of using AND you could hae used an ampersand(&). Before using this method, set define off so the & character will not be seen as part of a variable name. SQL> set define off SQL> select * from books where contains(info, 'property & harvests') > 0; SQL> select * from books where catsearch(info, 'property harvests', null) > 0; The following queries will search for more than two words. SQL> select * from books where contains(info, 'property AND harvests AND workers') > 0; SQL> select * from books where catsearch(info, 'property harvests workers', null) > 0; The following queries will search for either of the two words. SQL> select * from books where contains(info, 'property OR harvests') > 0; Instead of OR you can use a vertical line (|). SQL> select * from books where contains(info, 'property | harvests') > 0; SQL> select * from books where catsearch(info, 'property | harvests', null) > 0; In the following queries the ACCUM(accumulate) operator adds together the scores of the individual searches and compares the accumulated score to the threshold value. SQL> select * from books where contains(info, 'property ACCUM harvests') > 0; SQL> select * from books where catsearch(info, 'property ACCUM harvests', null) > 0; Instead of OR you can use a comma(,). SQL> select * from books where contains(info, 'property , harvests') > 0; SQL> select * from books where catsearch(info, 'property , harvests', null) > 0; In the following queries the MINUS operator subtracts the score of the second term's search from the score of the first term's search. SQL> select * from books where contains(info, 'property MINUS harvests') > 0; SQL> select * from books where catsearch(info, 'property NOT harvests', null) > 0; Instead of MINUS you can use - and instead of NOT you can use ~. SQL> select * from books where contains(info, 'property - harvests') > 0; SQL> select * from books where catsearch(info, 'property ~ harvests', null) > 0; SEARCHING FOR AN EXACT MATCH OF A PHRASEThe following queries will search for the phrase.If the search phrase includes a reserved word within oracle text, the you must use curly braces ({}) to enclose text. SQL> select * from books where contains(info, 'transactions {and} finances') > 0; SQL> select * from books where catsearch(info, 'transactions {and} finances', null) > 0; You can enclose the entire phrase within curly braces, in which case any reserved words within the phrase will be treated as part of the search criteria. SQL> select * from books where contains(info, '{transactions and finances}') > 0; SQL> select * from books where catsearch(info, '{transactions and finances}', null) > 0; SEARCHING FOR WORDS THAT ARE NEAR EACH OTHERThe following queries will search for the words that are in between the search terms.SQL> select * from books where contains(info, 'workers NEAR harvests') > 0; Instead of NEAR you can use ;. SQL> select * from books where contains(info, 'workers ; harvests') > 0; In CONTEXT index queries, you can specify the maximum number of words between the search terms. SQL> select * from books where contains(info, 'NEAR((workers, harvests),10)' > 0; USING WILDCARDS DURING SEARCHESYou can use wildcards to expand the list of valid search terms used during your query.Just as in regular text-string wildcard processing, two wildcards are available. % - percent sign; multiple-character wildcard _ - underscore; single-character wildcard SQL> select * from books where contains(info, 'worker%') > 0; SQL> select * from books where contains(info, 'work___') > 0; SEARCHING FOR WORDS THAT SHARE THE SAME STEMRather than using wildcards, you can use stem-expansion capabilities to expand the list of text strings.Given the 'stem' of a word, oracle will expand the list of words to search for to include all words having the same stem. Sample expansions are show here. Play - plays playing played playful SQL> select * from books where contains(info, '$manage') > 0; SEARCHING FOR FUZZY MATCHES
SQL> select * from books where contains(info, 'hardest') > 0;
SQL> select * from books where contains(info, '?hardest') > 0; SEARCHING FOR WORDS THAT SOUND LIKE OTHER WORDS
INDEX SYNCHRONIZATION
INDEX SETS
SQL> exec CTX_DDL.CREATE_INDEX_SET('books_index_set'); The add non-text indexes. SQL> exec CTX_DDL.ADD_INDEX('books_index_set', 'title_index'); Now create a CTXCAT text index. Specify ctxsys.ctxcat as the index type, and list the index set in the parameters clause. SQL> create index book_index on books(info) indextype is ctxsys.ctxcat parameters('index set books_index_set'); INDEX-ORGANIZED TABLE
Ex: SQL> create table student (sno number(2),sname varchar(10),smarks number(3) constraint pk primary key(sno) organization index; PARTITION INDEX
LOCAL INDEXES
Ex: SQL> create index stud_index on student(sno) local; GLOBAL INDEXES
Ex: SQL> create index stud_index on student(sno) global;
Ex: SQL> alter index stud_ind rebuild partition p2
MONITORING USE OF INDEXES
Syntax: alter index index_name monitoring usage; then check for the details in V$OBJECT_USAGE view. If you want to stop monitoring use the following. Syntax: alter index index_name nomonitoring usage; DATA MODEL
SQL*PLUS COMMNANDSThese commands does not require statement terminator and applicable to the sessions , those will be automatically cleared when session was closed. BREAKThis will be used to breakup the data depending on the grouping.Syntax: Break or bre [on <column_name> on report] COMPUTEThis will be used to perform group functions on the data.Syntax: Compute or comp [group_function of column_name on breaking_column_name or report] TTITLEThis will give the top title for your report. You can on or off the ttitle.Syntax: Ttitle or ttit [left | center | right] title_name skip n other_characters Ttitle or ttit [on or off] BTITLEThis will give the bottom title for your report. You can on or off the btitle.Syntax: Btitle or btit [left | center | right] title_name skip n other_characters Btitle or btit [on or off] Ex: SQL> bre on deptno skip 1 on report SQL> comp sum of sal on deptno SQL> comp sum of sal on report SQL> ttitle center 'EMPLOYEE DETAILS' skip1 center '----------------' SQL> btitle center '** THANKQ **' SQL> select * from emp order by deptno; Output:
EMPLOYEE DETAILS
-----------------------
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
------ ------- -------- ------- --------- -------- ------ ----------
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7839 KING PRESIDENT 17-NOV-81 5000
7934 MILLER CLERK 7782 23-JAN-82 1300
--------- **********
8750 sum
7369 SMITH CLERK 7902 17-DEC-80 800 20
7876 ADAMS CLERK 7788 23-MAY-87 1100
7902 FORD ANALYST 7566 03-DEC-81 3000
7788 SCOTT ANALYST 7566 19-APR-87 3000
7566 JONES MANAGER 7839 02-APR-81 2975
---------- **********
10875 sum
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400
7900 JAMES CLERK 7698 03-DEC-81 950
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0
7521 WARD SALESMAN 7698 22-FEB-81 1250 500
---------- **********
9400 sum
----------
sum 29025
CLEARThis will clear the existing buffers or break or computations or columns formatting.Syntax: Clear or cle buffer | bre | comp | col; Ex: SQL> clear buffer Buffer cleared SQL> clear bre Breaks cleared SQL> clear comp Computes cleared SQL> clear col Columns cleared CHANGEThis will be used to replace any strings in SQL statements.Syntax: Change or c/old_string/new_string If the old_string repeats many times then new_string replaces the first string only. Ex: SQL> select * from det; select * from det * ERROR at line 1: ORA-00942: table or view does not exist SQL> c/det/dept 1* select * from dept SQL> /
DEPTNO DNAME LOC
---------- ------------ -----------
10 ACCOUNTING NEW YORK
20 RESEARCH ALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
COLUMNThis will be used to increase or decrease the width of the table columns.Syntax: Column or col <column_name> format <num_format|text_format> Ex: SQL> col deptno format 999 SQL> col dname format a10 SAVEThis will be used to save your current SQL statement as SQL Script file.Syntax: Save or sav <file_name>.[extension] replace or rep If you want to save the filename with existing filename the you have to use replace option. By default it will take sql as the extension. Ex: SQL> save ss Created file ss.sql SQL> save ss replace Wrote file ss.sql EXECUTEThis will be used to execute stored subprograms or packaged subprograms.Syntax: Execute or exec <subprogram_name> Ex: SQL> exec sample_proc SPOOLThis will record the data when you spool on, upto when you say spool off. By default it will give lst as extension.Syntax: Spool on | off | out | <file_name>.[Extension] Ex: SQL> spool on SQL> select * from dept;
DEPTNO DNAME LOC
------- ------------ ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
SQL> spool off SQL> ed on.lst SQL> select * from dept;
DEPTNO DNAME LOC
------ ------------ ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
SQL> spool off LISTThis will give the current SQL statement.Syntax: List or li [start_line_number] [end_line_number] Ex: SQL> select 2 * 3 from 4 dept; SQL> list 1 select 2 * 3 from 4 * dept SQL> list 1 1 * select SQL> list 3 3 * from SQL> list 1 3 1 select 2 * 3 * from INPUTThis will insert the new line to the current SQL statement.Syntax: Input or in <string> Ex: SQL> select * SQL> list 1 * select * SQL> input from dept SQL> list 1 select * 2 * from dept APPENDThis will adds a new string to the existing string in the SQL statement without any space.Syntax: Append or app <string> Ex: SQL> select * SQL> list 1 * select * SQL> append from dept 1 * select * from dept SQL> list 1 * select * from dept DELETEThis will delete the current SQL statement lines.Syntax: Delete or del <start_line_number> [<end_line_number>] Ex: SQL> select 2 * 3 from 4 dept 5 where 6 deptno 7 >10; SQL> list 1 select 2 * 3 from 4 dept 5 where 6 deptno 7 * >10 SQL> del 1 SQL> list 1 * 2 from 3 dept 4 where 5 deptno 6 * >10 SQL> del 2 SQL> list 1 * 2 dept 3 where 4 deptno 5 * >10 SQL> del 2 4 SQL> list 1 * 2 * >10 SQL> del SQL> list 1 * VARIABLEThis will be used to declare a variable.Syntax: Variable or var <variable_name> <variable_type> Ex: SQL> var dept_name varchar(15) SQL> select dname into dept_name from dept where deptno = 10; Syntax: Print <variable_name> Ex: SQL> print dept_name DEPT_NAME -------------- ACCOUNTING STARTThis will be used to execute SQL scripts.Syntax: start <filename_name>.sql Ex: SQL> start ss.sql SQL> @ss.sql -- this will execute sql script files only. HOSTThis will be used to interact with the OS level from SQL.Syntax: Host [operation] Ex: SQL> host SQL> host dir SHOWUsing this, you can see several commands that use the set command and status.Syntax: Show all | <set_command> Ex: SQL> show all appinfo is OFF and set to "SQL*Plus" arraysize 15 autocommit OFF autoprint OFF autorecovery OFF autotrace OFF blockterminator "." (hex 2e) btitle OFF and is the first few characters of the next SELECT statement cmdsep OFF colsep " " compatibility version NATIVE concat "." (hex 2e) copycommit 0 COPYTYPECHECK is ON define "&" (hex 26) describe DEPTH 1 LINENUM OFF INDENT ON echo OFF editfile "afiedt.buf" embedded OFF escape OFF FEEDBACK ON for 6 or more rows flagger OFF flush ON SQL> show verify verify OFF RUNThis will runs the command in the buffer.Syntax: Run | / Ex: SQL> run SQL> / STOREThis will save all the set command statuses in a file.Syntax: Store set <filename>.[extension] [create] | [replace] | [append] Ex: SQL> store set my_settings.scmd Created file my_settings.scmd SQL> store set my_settings.cmd replace Wrote file my_settings.cmd SQL> store set my_settings.cmd append Appended file to my_settings.cmd FOLD_AFTERThis will fold the columns one after the other.Syntax: Column <column_name> fold_after [no_of_lines] Ex: SQL> col deptno fold_after 1 SQL> col dname fold_after 1 SQL> col loc fold_after 1 SQL> set heading off SQL> select * from dept;
10
ACCOUNTING
NEW YORK
20
RESEARCH
DALLAS
30
SALES
CHICAGO
40
OPERATIONS
BOSTON
FOLD_BEFOREThis will fold the columns one before the other.Syntax: Column <column_name> fold_before [no_of_lines] DFINEThis will give the list of all the variables currently defined.Syntax: Define [variable_name] Ex: SQL> define
DEFINE _DATE = "16-MAY-07" (CHAR)
DEFINE _CONNECT_IDENTIFIER = "oracle" (CHAR)
DEFINE _USER = "SCOTT" (CHAR)
DEFINE _PRIVILEGE = "" (CHAR)
DEFINE _SQLPLUS_RELEASE = "1001000200" (CHAR)
DEFINE _EDITOR = "Notepad" (CHAR)
DEFINE _O_VERSION = "Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 -
Production With the Partitioning, OLAP and Data Mining
options" (CHAR)
DEFINE _O_RELEASE = "1001000200" (CHAR)
SET COMMANDSThese commands does not require statement terminator and applicable to the sessions , those will be automatically cleared when session was closed.LINESIZEThis will be used to set the linesize.Default linesize is 80. Syntax: Set linesize <value> Ex: SQL> set linesize 100 PAGESIZEThis will be used to set the pagesize.Default pagesize is 14. Syntax: Set pagesize <value> Ex: SQL> set pagesize 30 DESCRIBEThis will be used to see the object's structure.Syntax: Describe or desc <object_name> Ex: SQL> desc dept Name Null? Type --------- ------------- ------------ DEPTNO NOT NULL NUMBER(2) DNAME VARCHAR2(14) LOC VARCHAR2(13) PAUSE
Syntax: Set pause on | off Ex: SQL> set pause on FEEDBACK
Syntax: Set feedback <value> Ex: SQL> set feedback 4 SQL> select * from dept;
DEPTNO DNAME LOC
-------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
4 rows selected.
HEADING
Syntax: Set heading on | off Ex: SQL> set heading off SQL> select * from dept;
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
SERVEROUTPUT
Syntax: Set serveroutput on | off Ex: SQL> set serveroutput on TIME
Syntax: Set time on | off Ex: SQL> set time on 19:56:33 SQL> TIMING
Syntax: Set timing on | off Ex: SQL> set timing on SQL> select * from dept;
DEPTNO DNAME LOC
-------- ---------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Elapsed: 00:00:00.06
SQLPROMPTThis will be used to change the SQL prompt.Syntax: Set sqlprompt <prompt> Ex: SQL> set sqlprompt 'ORACLE>' ORACLE> SQLCASE
Syntax: Set sqlcase upper | mixed | lower Ex: SQL> set sqlcase upper SQLTERMINATOR
Syntax: Set sqlterminator <termination_character> Ex: SQL> set sqlterminator : SQL> select * from dept: DEFINE
Syntax: Set define on | off Ex: SQL>insert into dept values(50,'R&D','HYD'); Enter value for d: old 1: insert into dept values(50,'R&D','HYD') new 1: INSERT INTO DEPT VALUES(50,'R','HYD') SQL> set define off SQL>insert into dept values(50,'R&D','HYD'); -- here it won't ask for value NEWPAGE
Syntax: Set newpage <value> Ex: SQL> set newpage 10
HEADSEP
Syntax: Set headsep <separation_char> Ex: SQL> select * from dept;
DEPTNO DNAME LOC
------- ----------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
SQL> set headsetp ! SQL> col dname heading 'DEPARTMENT ! NAME' SQL> /
DEPARTMENT
ECHO
Syntax: Set echo on | off VERIFY
Syntax: Set verify on | off Ex: SQL> select * from dept where deptno = &dno;
Enter value for dno: 10
old 1: select * from dept where deptno = &dno
new 1: select * from dept where deptno = 10
DEPTNO DNAME LOC
-------- ------------ -----------
10 ACCOUNTING NEW YORK
SQL> set verify off SQL> select * from dept where deptno = &dno;
Enter value for dno: 20
DEPTNO DNAME LOC
-------- ---------- -----------
20 RESEARCH DALLAS
PNO
Ex: SQL> col hiredate new_value xtoday noprint format a1 trunc SQL> ttitle left xtoday right 'page' sql.pno SQL> select * from emp where deptno = 10; 09-JUN-81 page 1 EMPNO ENAME JOB MGR SAL COMM DEPTNO ------ -------- ---------- ------- ----- ----- -------- 7782 CLARK MANAGER 7839 2450 10 7839 KING PRESIDENT 5000 10 7934 MILLER CLERK 7782 1300 10
SPECIAL FILESLOGIN.sql
GLOGIN.sqlThis is used in the same ways as LOGIN.sql but to establish default SQLPLUS settings for all users of a database.IMP QUERIES
INTRODUCTIONCHARACTERSTICS
10g FEATURES
ANONYMOUS BLOCKSAnonymous blocks implies basic block structure.Ex:
BEGIN
Dbms_output.put_line('My first program'):
END;
LABELED BLOCKSLabeled blocks are anonymous blocks with a label which gives a name to the block.Ex:
<<my_bloock>>
BEGIN
Dbms_output.put_line('My first program'):
END;
SUBPROGRAMSSubprograms are procedures and functions. They can be stored in the database as stand-alone objects, as part of package or as methods of an object type. TRIGGERSTriggers consists of a PL/SQL block that is associated with an event that occur in the database. NESTED BLOCKSA block can be nested within the executable or exception section of an outer block. IDENTIFIERSIdentifiers are used to name PL/SQL objects, such as variables, cursors, types and subprograms. Identifiers consists of a letter, optionally followed by any sequence of characters, including letters, numbers, dollar signs, underscores, and pound signs only. The maximum length for an identifier is 30 characters. QUOTED IDENTIFIERSIf you want to make an identifier case sensitive, include characters such as spaces or use a reserved word, you can enclose the identifier in double quotation marks. Ex:
DECLARE
"a" number := 5;
"A" number := 6;
BEGIN
dbms_output.put_line('a = ' || a);
dbms_output.put_line('A = ' || A);
END;
Output:
a = 6
A = 6
COMMENTSComments improve readability and make your program more understandable. They are ignored by the PL/SQL compiler. There are two types of comments available.
SINGLE LINE COMMENTSA single-line comment can start any point on a line with two dashes and continues until the end of the line.Ex:
BEGIN
Dbms_output.put_line('hello'); -- sample program
END;
MULTILINE COMMENTSMultiline comments start with the /* delimiter and ends with */ delimiter.Ex:
BEGIN
Dbms_output.put_line('hello'); /* sample program */
END;
VARIABLE DECLERATIONSVariables can be declared in declarative section of the block;Ex:
DECLARE
a number;
b number := 5;
c number default 6;
CONSTANT DECLERATIONSTo declare a constant, you include the CONSTANT keyword, and you must supply a default value.Ex:
DECLARE
b constant number := 5;
c constant number default 6;
NOT NULL CLAUSEYou can also specify that the variable must be not null.Ex:
DECLARE
b constant number not null:= 5;
c number not null default 6;
ANCHORED DECLERATIONSPL/SQL offers two kinds of achoring.
SCALAR ANCHORINGUse the %TYPE attribute to define your variable based on table's column of some other PL/SQL scalar variable.Ex:
DECLARE
dno dept.deptno%type;
Subtype t_number is number;
a t_number;
Subtype t_sno is student.sno%type;
V_sno t_sno;
RECORD ANCHORINGUse the %ROWTYPE attribute to define your record structure based on a table.Ex: DECLARE V_dept dept%rowtype; BENEFITS OF ANCHORED DECLARATIONS
PROGRAMMER-DEFINED TYPESWith the SUBTYPE statement, PL/SQL allows you to define your own subtypes or aliases of predefined datatypes, sometimes referred to as abstract datatypes.There are two kinds of subtypes.
CONSTRAINED SUBTYPEA subtype that restricts or constrains the values normally allowd by the datatype itself.Ex: Subtype positive is binary_integer range 1..2147483647; In the above declaration a variable that is declared as positive can store only ingeger greater than zero even though binary_integer ranges from -2147483647..+2147483647. UNCONSTRAINED SUBTYPEA subtype that does not restrict the values of the original datatype in variables declared with the subtype.Ex: Subtype float is number; DATATYPE CONVERSIONSPL/SQL can handle conversions between different families among the datatypes. Conversion can be done in two ways.
EXPLICIT CONVERSIONThis can be done using the built-in functions available.IMPLICIT CONVERSIONPL/SQL will automatically convert between datatype families when possible.Ex:
DECLARE
a varchar(10);
BEGIN
select deptno into a from dept where dname='ACCOUNTING';
END;
In the above variable a is char type and deptno is number type even though, oracle will automatically converts the numeric data into char type assigns to the variable. PL/SQL can automatically convert between
VARIABLE SCOPE AND VISIBILITYThe scope of a variable is the portion of the program in which the variable can be accessed. For PL/SQL variables, this is from the variable declaration until the end of the block. When a variable goes out of scope, the PL/SQL engine will free the memory used to store the variable. The visibility of a variable is the portion of the program where the variable can be accessed without having to qualify the reference. The visibility is always within the scope. If it is out of scope, it is not visible. Ex1:
DECLARE
a number; -- scope of a
BEGIN
--------
DECLARE
b number; -- scope of b
BEGIN
-----
END;
------
END;
Ex2:
DECLARE
a number;
b number;
BEGIN
-- a , b available here
DECLARE
b char(10);
BEGIN
-- a and char type b is available here
END;
-----
END;
Ex3:
<<my_block>>
DECLARE
a number;
b number;
BEGIN
-- a , b available here
DECLARE
b char(10);
BEGIN
-- a and char type b is available here
-- number type b is available using <<my_block>>.b
END;
------
END;
PL/SQL CONTROL STRUCTURESPL/SQL has a variety of control structures that allow you to control the behaviour of the block as it runs.These structures include conditional statements and loops.
IF-THEN-ELSESyntax:
If <condition1> then
Sequence of statements;
Elsif <condition1> then
Sequence of statements;
......
Else
Sequence of statements;
End if;
Ex:
DECLARE
dno number(2);
BEGIN
select deptno into dno from dept where dname = 'ACCOUNTING';
if dno = 10 then
dbms_output.put_line('Location is NEW YORK');
elsif dno = 20 then
dbms_output.put_line('Location is DALLAS');
elsif dno = 30 then
dbms_output.put_line('Location is CHICAGO');
else
dbms_output.put_line('Location is BOSTON');
end if;
END;
Output:
Location is NEW YORK
CASESyntax:Case test-variable When value1 then sequence of statements; When value2 then sequence of statements; ...... When valuen then sequence of statements; Else sequence of statements; End case; Ex:
DECLARE
dno number(2);
BEGIN
select deptno into dno from dept where dname = 'ACCOUNTING';
case dno
when 10 then
dbms_output.put_line('Location is NEW YORK');
when 20 then
dbms_output.put_line('Location is DALLAS');
when 30 then
dbms_output.put_line('Location is CHICAGO');
else
dbms_output.put_line('Location is BOSTON');
end case;
END;
Output:
Location is NEW YORK
CASE WITHOUT ELSESyntax:Case test-variable When value1 then sequence of statements; When value2 then sequence of statements; ...... When valuen then sequence of statements; End case; Ex:
DECLARE
dno number(2);
BEGIN
select deptno into dno from dept where dname = 'ACCOUNTING';
case dno
when 10 then
dbms_output.put_line('Location is NEW YORK');
when 20 then
dbms_output.put_line('Location is DALLAS');
when 30 then
dbms_output.put_line('Location is CHICAGO');
when 40 then
dbms_output.put_line('Location is BOSTON');
end case;
END;
Output:
Location is NEW YORK
LABELED CASESyntax:<<label>> Case test-variable When value1 then sequence of statements; When value2 then sequence of statements; ...... When valuen then sequence of statements; End case; Ex:
DECLARE
dno number(2);
BEGIN
select deptno into dno from dept where dname = 'ACCOUNTING';
<<my_case>>
case dno
when 10 then
dbms_output.put_line('Location is NEW YORK');
when 20 then
dbms_output.put_line('Location is DALLAS');
when 30 then
dbms_output.put_line('Location is CHICAGO');
when 40 then
dbms_output.put_line('Location is BOSTON');
end case my_case;
END;
Output:
Location is NEW YORK
SEARCHED CASESyntax:Case When <condition1> then sequence of statements; When <condition2> then sequence of statements; ...... When <conditionn> then sequence of statements; End case; Ex:
DECLARE
dno number(2);
BEGIN
select deptno into dno from dept where dname = 'ACCOUNTING';
case dno
when dno = 10 then
dbms_output.put_line('Location is NEW YORK');
when dno = 20 then
dbms_output.put_line('Location is DALLAS');
when dno = 30 then
dbms_output.put_line('Location is CHICAGO');
when dno = 40 then
dbms_output.put_line('Location is BOSTON');
end case;
END;
Output:
Location is NEW YORK
SIMPLE LOOPSyntax:Loop Sequence of statements; Exit when <condition>; End loop;In the syntax exit when <condition> is equivalent to If <condition> then Exit; End if; Ex:
DECLARE
i number := 1;
BEGIN
loop
dbms_output.put_line('i = ' || i);
i := i + 1;
exit when i > 5;
end loop;
END;
Output:
i = 1
i = 2
i = 3
i = 4
i = 5
WHILE LOOPSyntax:While <condition> loop Sequence of statements; End loop; Ex:
DECLARE
i number := 1;
BEGIN
While i <= 5 loop
dbms_output.put_line('i = ' || i);
i := i + 1;
end loop;
END;
Output:
i = 1
i = 2
i = 3
i = 4
i = 5
FOR LOOPSyntax:For <loop_counter_variable> in low_bound..high_bound loop Sequence of statements; End loop;Ex1:
BEGIN
For i in 1..5 loop
dbms_output.put_line('i = ' || i);
end loop;
END;
Output:
i = 1
i = 2
i = 3
i = 4
i = 5
Ex2:
BEGIN
For i in reverse 1..5 loop
dbms_output.put_line('i = ' || i);
end loop;
END;
Output:
i = 5
i = 4
i = 3
i = 2
i = 1
NULL STATEMENTUsually when you write a statement in a program, you want it to do something.There are cases, however, when you want to tell PL/SQL to do absolutely nothing, and that is where the NULL comes. The NULL statement deos nothing except pass control to the next executable statement. You can use NULL statement in the following situations.
GOTO AND LABELSSyntax:Goto label;Where label is a label defined in the PL/SQL block. Labels are enclosed in double angle brackets. When a goto statement is evaluated, control immediately passes to the statement identified by the label. Ex:
BEGIN
For i in 1..5 loop
dbms_output.put_line('i = ' || i);
if i = 4 then
goto exit_loop;
end if;
end loop;
<<exit_loop>>
Null;
END;
Output:
i = 1
i = 2
i = 3
i = 4
RESTRICTIONS ON GOTO
PRAGMASPragmas are compiler directives. They serve as instructions to the PL/SQL compiler. The compiler will act on the pragma during the compilation of the block.Syntax: PRGAMA instruction_to_compiler.PL/SQL offers several pragmas:
SUBPROGRAMSPROCEDURESA procedure is a module that performs one or more actions.Syntax:
Procedure [schema.]name [(parameter1 [,parameter2 ...])]
[authid definer | current_user] is
-- [declarations]
Begin
-- executable statements
[Exception
-- exception handlers]
End [name];
In the above authid clause defines whether the procedure will execute under the authority of the definer of the procedure or under the authority of the current user. FUNCTIONSA function is a module that returns a value.Syntax:
Function [schema.]name [(parameter1 [,parameter2 ...])]
Return return_datatype
[authid definer | current_user]
[deterministic]
[parallel_enable] is
-- [declarations]
Begin
-- executable statements
[Exception
-- exception handlers]
End [name];
In the above authid clause defines whether the procedure will execute under the authority of the definer of the procedure or under the authority of the current user. Deterministic clause defines, an optimization hint that lets the system use a saved copy of the function's return result, if available. The quety optimizer can choose whether to use the saved copy or re-call the function. Parallel_enable clause defines, an optimization hint that enables the function to be executed in parallel when called from within SELECT statement. PARAMETER MODES
INIn parameter will act as pl/sql constant.OUT
IN OUT
DEFAULT PARAMETERS
procedure p(a in number default 5, b in number default 6, c in number default 7) - valid procedure p(a in number, b in number default 6, c in number default 7) - valild procedure p(a in number, b in number, c in number default 7) - valild procedure p(a in number, b in number default 6, c in number) - invalild procedure p(a in number default 5, b in number default 6, c in number) - invalild procedure p(a in number default 5, b in number, c in number) - invalild NOTATIONSNotations are of two types.
Ex: Suppose we have a procedure proc(a number,b number,c number) and we have one anonymous block which contains v1,v2, and v3; SQL> exec proc (v1,v2,v3) -- Positional notation SQL> exec proc (a=>v1,b=>v2,c=>v3) -- Named notation FORMAL AND ACTUAL PARAMETERS
CREATE OR REPLACE PROCEDURE SAMPLE(a in number,b out number,c in out number) is
BEGIN
dbms_output.put_line('After call');
dbms_output.put_line('a = ' || a ||' b = ' || b || ' c = ' || c);
b := 10;
c := 20;
dbms_output.put_line('After assignment');
dbms_output.put_line('a = ' || a ||' b = ' || b || ' c = ' || c);
END SAMPLE;
DECLARE
v1 number := 4;
v2 number := 5;
v3 number := 6;
BEGIN
dbms_output.put_line('Before call');
dbms_output.put_line('v1 = ' || v1 || ' v2 = ' || v2 || ' v3 = ' || v3);
sample(v1,v2,v3);
dbms_output.put_line('After completion of call');
dbms_output.put_line('v1 = ' || v1 || ' v2 = ' || v2 || ' v3 = ' || v3);
END;
Output:
Before call
v1 = 4 v2 = 5 v3 = 6
After call
a = 4 b = c = 6
After assignment
a = 4 b = 10 c = 20
After completion of call
v1 = 4 v2 = 10 v3 = 20
Ex2:
CREATE OR REPLACE FUN(a in number,b out number,c in out number) return number IS
BEGIN
dbms_output.put_line('After call');
dbms_output.put_line('a = ' || a || ' b = ' || b || ' c = ' || c);
dbms_output.put_line('Before assignement Result = ' || (a*nvl(b,1)*c));
b := 5;
c := 7;
dbms_output.put_line('After assignment');
dbms_output.put_line('a = ' || a || ' b = ' || b || ' c = ' || c);
return (a*b*c);
END FUN;
DECLARE
v1 number := 1;
v2 number := 2;
v3 number := 3;
v number;
BEGIN
dbms_output.put_line('Before call');
dbms_output.put_line('v1 = ' || v1 || ' v2 = ' || v2 || ' v3 = ' || v3);
v := fun(v1,v2,v3);
dbms_output.put_line('After call completed');
dbms_output.put_line('v1 = ' || v1 || ' v2 = ' || v2 || ' v3 = ' || v3);
dbms_output.put_line('Result = ' || v);
END;
Output:
Before call
v1 = 1 v2 = 2 v3 = 3
After call
a = 1 b = c = 3
Before assignement Result = 3
After assignment
a = 1 b = 5 c = 7
After call completed
v1 = 1 v2 = 5 v3 = 7
Result = 35
RESTRICTIONS ON FORMAL PARAMETERS
USING NOCOPY
Ex:
CREATE OR REPLACE PROCEDURE PROC(a in out nocopy number) IS
BEGIN
----
END PROC;
CALL AND EXECCall is a SQL statement, which can be used to execute subprograms like exec. Syntax: Call subprogram_name([argument_list]) [into host_variable];
CREATE OR REPLACE PROC IS
BEGIN
dbms_output.put_line('hello world');
END PROC;
Output:
Ex2:
CREATE OR REPLACE PROC(a in number,b in number) IS
BEGIN
dbms_output.put_line('a = ' || a || ' b = ' || b);
END PROC;
Output:
Ex3:
CREATE OR REPLACE FUNCTION FUN RETURN VARCHAR IS
BEGIN
return 'hello world';
END FUN;
Output:
CALL BY REFERENCE AND CALL BY VALUE
SUBPROGRAMS OVERLOADING
Ex: SQL> create or replace type t1 as object(a number);/ SQL> create or replace type t1 as object(a number);/
DECLARE
i t1 := t1(5);
j t2 := t2(5);
PROCEDURE P(m t1) IS
BEGIN
dbms_output.put_line('a = ' || m.a);
END P;
PROCEDURE P(n t2) IS
BEGIN
dbms_output.put_line('b = ' || n.b);
END P;
PROCEDURE PRODUCT(a number,b number) IS
BEGIN
dbms_output.put_line('Product of a,b = ' || a * b);
END PRODUCT;
PROCEDURE PRODUCT(a number,b number,c number) IS
BEGIN
dbms_output.put_line('Product of a,b = ' || a * b * c);
END PRODUCT;
BEGIN
p(i);
p(j);
product(4,5);
product(4,5,6);
END;
Output:
a = 5
b = 5
Product of a,b = 20
Product of a,b = 120
BENEFITS OF OVERLOADING
RESTRICTIONS ON OVERLOADING
IMPORTANT POINTS ABOUT SUBPROGRAMS
PROCEDURES Vs FUNCTIONS
STORED Vs LOCAL SUBPROGRAMS
CREATE OR REPLACE PROCEDURE P IS
BEGIN
dbms_output.put_line('Stored subprogram');
END;
Output:
Ex2:
DECLARE
PROCEDURE P IS
BEGIN
dbms_output.put_line('Local subprogram');
END;
BEGIN
p;
END;
Output:
Local subprogram
COMPILING SUBPROGRAMSSQL> Alter procedure P1 compile;SQL> Alter function F1 compile; SUBPROGRAMS DEPENDECIES
SUBPROGRAMS DEPENDENCIES IN REMOTE DATABASES
TIMESTAMP MODEL
ISSUES WITH THIS MODEL
SIGNATURE MODEL
THREE WAYS OF SETTING THIS MODE
ISSUES WITH THIS MODEL
FORWARD DECLERATIONBefore going to use the procedure in any other subprogram or other block , you must declare the prototype of the procedure in declarative section.Ex1:
DECLARE
PROCEDURE P1 IS
BEGIN
dbms_output.put_line('From procedure p1');
p2;
END P1;
PROCEDURE P2 IS
BEGIN
dbms_output.put_line('From procedure p2');
p3;
END P2;
PROCEDURE P3 IS
BEGIN
dbms_output.put_line('From procedure p3');
END P3;
BEGIN
p1;
END;
Output:
p2;
*
ERROR at line 5:
ORA-06550: line 5, column 1:
PLS-00313: 'P2' not declared in this scope
ORA-06550: line 5, column 1:
PL/SQL: Statement ignored
ORA-06550: line 10, column 1:
PLS-00313: 'P3' not declared in this scope
ORA-06550: line 10, column 1:
PL/SQL: Statement ignored
Ex2:
DECLARE
PROCEDURE P2; -- forward declaration
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
dbms_output.put_line('From procedure p1');
p2;
END P1;
PROCEDURE P2 IS
BEGIN
dbms_output.put_line('From procedure p2');
p3;
END P2;
PROCEDURE P3 IS
BEGIN
dbms_output.put_line('From procedure p3');
END P3;
BEGIN
p1;
END;
Output:
From procedure p1
From procedure p2
From procedure p3
PRIVILEGES AND STORED SUBPROGRAMS
EXECUTE PREVILEGE
CREATE OR REPLACE PROCEDURE P IS
cursor is select *from student1;
BEGIN
for v in c loop
insert into student2 values(v.no,v.name,v.marks);
end loop;
END P;
userA granted execute privilege to userB using
SQL> grant execute on p to userB Then userB executed the procedure SQL> Exec userA.p If suppose userB also having student2 table then which table will populate whether userA's or userB's. The answer is userA's student2 table only because by default the procedure will execute under the privlige set of its owner. The above procedure is known as definer's procedure. HOW TO POPULATE USER B's TABLE
CREATE OR REPLACE PROCEDURE P
AUTHID CURRENT_USER IS
cursor is select *from student1;
BEGIN
for v in c loop
insert into student2 values(v.no,v.name,v.marks);
end loop;
END P;
Then grant execute privilege on p to userB.
Executing the procedure by userB, which populates userB's table. The above procedure is called invoker's procedure. Instead of current_user of authid clause, if you use definer then it will be called definer' procedure. STORED SUBPROGRAMS AND ROLES we have two users saketh and sudha in which saketh has student table and sudha does not. Sudha is going to create a procedure based on student table owned by saketh. Before doing this saketh must grant the permissions on this table to sudha. SQL> conn saketh/saketh SQL> grant all on student to sudha; then sudha can create procedure SQL> conn sudha/sudha
CREATE OR REPLACE PROCEDURE P IS
cursor c is select *from saketh.student;
BEGIN
for v in c loop
dbms_output.put_line('No = ' || v.no);
end loop;
END P;
here procedure will be created.
If the same privilege was granted through a role it wont create the procedure. Examine the following code SQL> conn saketh/saketh SQL> create role saketh_role; SQL> grant all on student to saketh_role; SQL> grant saketh_role to sudha; then conn sudha/sudha
CREATE OR REPLACE PROCEDURE P IS
cursor c is select *from saketh.student;
BEGIN
for v in c loop
dbms_output.put_line('No = ' || v.no);
end loop;
END P;
ISSUES WITH INVOKER'S RIGHTS
TRIGGERS, VIEWS AND INVOKER'S RIGHTS
PACKAGES
PACKAGE SYNTAXCreate or replace package <package_name> is -- package specification includes subprograms signatures,
Create or replace package body <package_name> is
-- package body includes body for all the subprograms declared
in the spec, private Variables and cursors.
Begin
-- initialization section
Exception
-- Exception handling seciton
End <package_name>;
IMPORTANT POINTS ABOUT PACKAGES
COMPILING PACKAGES
PACKAGE DEPENDENCIES
PACKAGE RUNTIME STATEPackage runtime state is differ for the following packages.
SERIALLY REUSABLE PACKAGESTo force the oracle to use serially reusable version then include PRAGMA SERIALLY_REUSABLE in both package spec and body,Examine the following package. CREATE OR REPLACE PACKAGE PKG IS pragma serially_reusable; procedure emp_proc; END PKG;
CREATE OR REPLACE PACKAGE BODY PKG IS
pragma serially_reusable;
cursor c is select ename from emp;
PROCEDURE EMP_PROC IS
v_ename emp.ename%type;
v_flag boolean := true;
v_numrows number := 0;
BEGIN
if not c%isopen then
open c;
end if;
while v_flag loop
fetch c into v_ename;
v_numrows := v_numrows + 1;
if v_numrows = 5 then
v_flag := false;
end if;
dbms_output.put_line('Ename = ' || v_ename);
end loop;
END EMP_PROC;
END PKG;
SQL> exec pkg.emp_proc
Ename = SMITH
Ename = ALLEN
Ename = WARD
Ename = JONES
Ename = MARTIN
SQL> exec pkg.emp_proc
Ename = SMITH
Ename = ALLEN
Ename = WARD
Ename = JONES
Ename = MARTIN
NON SERIALL Y REUSABLE PACKAGESThis is the default version used by the oracle,examine the following package. CREATE OR REPLACE PACKAGE PKG IS procedure emp_proc; END PKG;
CREATE OR REPLACE PACKAGE BODY IS
cursor c is select ename from emp;
PROCEDURE EMP_PROC IS
v_ename emp.ename%type;
v_flag boolean := true;
v_numrows number := 0;
BEGIN
if not c%isopen then
open c;
end if;
while v_flag loop
fetch c into v_ename;
v_numrows := v_numrows + 1;
if v_numrows = 5 then
v_flag := false;
end if;
dbms_output.put_line('Ename = ' || v_ename);
end loop;
END EMP_PROC;
END PKG;
SQL> exec pkg.emp_proc
Ename = SMITH
Ename = ALLEN
Ename = WARD
Ename = JONES
Ename = MARTIN
SQL> exec pkg.emp_proc
Ename = BLAKE
Ename = CLARK
Ename = SCOTT
Ename = KING
Ename = TURNER
DEPENDENCIES OF PACKAGE RUNTIME STATEDependencies can exists between package state and anonymous blocks.Examine the following program Create this package in first session CREATE OR REPLACE PACKAGE PKG IS v number := 5; procedure p; END PKG;
CREATE OR REPLACE PACKAGE BODY PKG IS
PROCEDURE P IS
BEGIN
dbms_output.put_line('v = ' || v);
v := 10;
dbms_output.put_line('v = ' || v);
END P;
END PKG;
Connect to second session, run the following code.
BEGIN pkg.p; END;The above code wil work. Go back to first session and recreate the package using create. Then connect to second session and run the following code again. BEGIN pkg.p; END;This above code will not work because of the following.
PURITY LEVELSIn general, calls to subprograms are procedural, they cannot be called from SQL statements.However, if a stand-alone or packaged function meets certain restrictions, it can be called during execution of a SQL statement. User-defined functions are called the same way as built-in functions but it must meet different restrictions. These restrictions are defined in terms of purity levels. There are four types of purity levels. WNDS -- Writes No Database State RNDS -- Reads No Database State WNPS -- Writes No Package State RNPS -- Reads No Package State In addition to the preceding restrictions, a user-defined function must also meet the following requirements to be called from a SQL statement.
RESTRICT_REFERENCESFor packaged functions, however, the RESTRICT_REFERENCES pragma is required to specify the purity level of a given function.Syntax: PRAGMA RESTRICT_REFERENCES(subprogram_name or package_name, WNDS [,WNPS] [,RNDS] [,RNPS]); Ex:
CREATE OR REPLACE PACKAGE PKG IS
function fun1 return varchar;
pragma restrict_references(fun1,wnds);
function fun2 return varchar;
pragma restrict_references(fun2,wnds);
END PKG;
CREATE OR REPLACE PACKAGE BODY PKG IS
FUNCTION FUN1 return varchar IS
BEGIN
update dept set deptno = 11;
return 'hello';
END FUN1;
FUNCTION FUN2 return varchar IS
BEGIN
update dept set dname ='aa';
return 'hello';
END FUN2;
END PKG;
The above package body will not created, it will give the following erros.
PLS-00452: Subprogram 'FUN1' violates its associated pragma PLS-00452: Subprogram 'FUN2' violates its associated pragma
CREATE OR REPLACE PACKAGE BODY PKG IS
FUNCTION FUN1 return varchar IS
BEGIN
return 'hello';
END FUN1;
FUNCTION FUN2 return varchar IS
BEGIN
return 'hello';
END FUN2;
END PKG;
Now the package body will be created.
DEFAULT
Ex: CREATE OR REPLACE PACKAGE PKG IS pragma restrict_references(default,wnds); function fun1 return varchar; function fun2 return varchar; END PKG;
CREATE OR REPLACE PACKAGE BODY PKG IS
FUNCTION FUN1 return varchar IS
BEGIN
update dept set deptno = 11;
return 'hello';
END FUN1;
FUNCTION FUN2 return varchar IS
BEGIN
update dept set dname ='aa';
return 'hello';
END FUN2;
END PKG;
The above package body will not created, it will give the following erros because the pragma will apply to all the functions.
PLS-00452: Subprogram 'FUN1' violates its associated pragma PLS-00452: Subprogram 'FUN2' violates its associated pragma
CREATE OR REPLACE PACKAGE BODY PKG IS
FUNCTION FUN1 return varchar IS
BEGIN
return 'hello';
END FUN1;
FUNCTION FUN2 return varchar IS
BEGIN
return 'hello';
END FUN2;
END PKG;
Now the package body will be created.
TRUSTIf the TRUST keyword is present, the restrictions listed in the pragma are not enforced.Rather, they are trusted to be true. Ex: CREATE OR REPLACE PACKAGE PKG IS function fun1 return varchar; pragma restrict_references(fun1,wnds,trust); function fun2 return varchar; pragma restrict_references(fun2,wnds,trust); END PKG;
CREATE OR REPLACE PACKAGE BODY PKG IS
FUNCTION FUN1 return varchar IS
BEGIN
update dept set deptno = 11;
return 'hello';
END FUN1;
FUNCTION FUN2 return varchar IS
BEGIN
update dept set dname ='aa';
return 'hello';
END FUN2;
END PKG;
The above package will be created successfully.
IMPORTANT POINTS ABOUT RESTRICT_REFERENCES
PINNING IN THE SHARED POOLThe shared pool is the portion of the SGS that contains, among other things, the p-code of compiled subprograms as they are run.The first time a stored a store subprogram is called, the p-code is loaded from disk into the shared pool. Once the object is no longer referenced, it is free to be aged out. Objects are aged out of the shared pool using an LRU(Least Recently Used) algorithm. The DBMS_SHARED_POOL package allows you to pin objects in the shared pool. When an object is pinned, it will never be aged out until you request it, no matter how full the pool gets or how often the object is accessed. This can improve performance, as it takes time to reload a package from disk. DBMS_SHARED_POOL has four procedures
KEEPThe DBMS_SHARED_POOL.KEEP procedure is used to pin objects in the pool.Syntax: PROCEDURE KEEP(object_name varchar2,flag char default 'P'); Here the flag represents different types of flag values for different types of objects. P -- Package, function or procedure Q -- Sequence R -- Trigger C -- SQL Cursor T -- Object type JS -- Java source JC -- Java class JR -- Java resource JD -- Java shared data UNKEEPUNKEEP is the only way to remove a kept object from the shared pool, without restarting the database. Kept objects are never aged out automatically.Syntax: PROCEDURE UNKEEP(object_name varchar2, flag char default 'P'); SIZESSIZES will echo the contents of the shared pool to the screen.Syntax: PROCEDURE SIZES(minsize number); Objects with greater than the minsize will be returned. SIZES uses DBMS_OUTPUT to return the data. ABORTED_REQUEST_THRESHOLDWhen the database determines that there is not enough memory in the shared pool to satisfy a given request, it will begin aging objects out until there is enough memory. It enough objects are aged out, this can have a performance impact on other database sessions. The ABORTED_REQUEST_THRESHOLD can be used to remedy this.Syntax: PROCEDURE ABORTED_REQUEST_THRESHOLD(threshold_size number); Once this procedure is called, oracle will not start aging objects from the pool unless at least threshold_size bytes is needed. DATA MODEL FOR SUBPROGRAMS AND PACKAGES
CURSORSCursor is a pointer to memory location which is called as context area which contains the information necessary for processing, including the number of rows processed by the statement, a pointer to the parsed representation of the statement, and the active set which is the set of rows returned by the query. Cursor contains two parts
Body includes the select statement. Ex: Cursor c(dno in number) return dept%rowtype is select *from dept; In the above Header - cursor c(dno in number) return dept%rowtype Body - select *from dept CURSOR TYPES
CURSOR STAGES
CURSOR ATTRIBUTES
CURSOR DECLERATIONSyntax: Cursor <cursor_name> is select statement; Ex: Cursor c is select *from dept; CURSOR LOOPS
SIMPLE LOOPSyntax:
Loop
Fetch <cursor_name> into <record_variable>;
Exit when <cursor_name> % notfound;
<statements>;
End loop;
Ex:
DECLARE
cursor c is select * from student;
v_stud student%rowtype;
BEGIN
open c;
loop
fetch c into v_stud;
exit when c%notfound;
dbms_output.put_line('Name = ' || v_stud.name);
end loop;
close c;
END;
Output:
Name = saketh
Name = srinu
Name = satish
Name = sudha
WHILE LOOPSyntax:
While <cursor_name> % found loop
Fetch <cursor_name> nto <record_variable>;
<statements>;
End loop;
Ex:
DECLARE
cursor c is select * from student;
v_stud student%rowtype;
BEGIN
open c;
fetch c into v_stud;
while c%found loop
fetch c into v_stud;
dbms_output.put_line('Name = ' || v_stud.name);
end loop;
close c;
END;
Output:
Name = saketh
Name = srinu
Name = satish
Name = sudha
FOR LOOPSyntax:
for <record_variable> in <cursor_name> loop
<statements>;
End loop;
Ex:
DECLARE
cursor c is select * from student;
BEGIN
for v_stud in c loop
dbms_output.put_line('Name = ' || v_stud.name);
end loop;
END;
Output:
Name = saketh
Name = srinu
Name = satish
Name = sudha
PARAMETARIZED CURSORS
Ex:
DECLARE
cursor c(dno in number) is select * from dept where deptno = dno;
v_dept dept%rowtype;
BEGIN
open c(20);
loop
fetch c into v_dept;
exit when c%notfound;
dbms_output.put_line('Dname = ' || v_dept.dname ||
PACKAGED CURSORS WITH HEADER IN SPEC AND BODY IN PACKAGE BODY
Ex:
CREATE OR REPLACE PACKAGE PKG IS
cursor c return dept%rowtype is select * from dept;
CREATE OR REPLACE PAKCAGE BODY PKG IS
cursor c return dept%rowtype is select * from dept;
PROCEDURE PROC IS
BEGIN
for v in c loop
dbms_output.put_line('Deptno = ' || v.deptno || ' Dname = ' ||
CREATE OR REPLACE PAKCAGE BODY PKG IS
cursor c return dept%rowtype is select * from dept where deptno > 20;
PROCEDURE PROC IS
BEGIN
for v in c loop
dbms_output.put_line('Deptno = ' || v.deptno || ' Dname = ' ||
REF CURSORS AND CURSOR VARIABLES
Ex: CREATE OR REPLACE PROCEDURE REF_CURSOR(TABLE_NAME IN VARCHAR) IS CURSOR EXPRESSIONS
USING NESTED CURSORS OR CURSOR EXPRESSIONSEx: DECLARE cursor c is select ename,cursor(select dname from dept d CURSOR CLAUSES
RETURNCursor c return dept%rowtype is select *from dept;Or Cursor c1 is select *from dept; Cursor c return c1%rowtype is select *from dept; Or Type t is record(deptno dept.deptno%type, dname dept.dname%type); Cursor c return t is select deptno, dname from dept; FOR UPDATE AND WHERE CURRENT OFNormally, a select operation will not take any locks on the rows being accessed.This will allow other sessions connected to the database to change the data being selected. The result set is still consistent. At open time, when the active set is determined, oracle takes a snapshot of the table. Any changes that have been committed prior to this point are reflected in the active set. Any changes made after this point, even if they are committed, are not reflected unless the cursor is reopened, which will evaluate the active set again. However, if the FOR UPDATE caluse is pesent, exclusive row locks are taken on the rows in the active set before the open returns. These locks prevent other sessions from changing the rows in the active set until the transaction is committed or rolled back. If another session already has locks on the rows in the active set, then SELECT ... FOR UPDATE operation will wait for these locks to be released by the other session. There is no time-out for this waiting period. The SELECT...FOR UPDATE will hang until the other session releases the lock. To handle this situation, the NOWAIT clause is available. Syntax: Select ...from ... for update of column_name [wait n]; If the cursor is declared with the FOR UPDATE clause, the WHERE CURRENT OF clause can be used in an update or delete statement. Syntax: Where current of cursor; Ex:
DECLARE
cursor c is select * from dept for update of dname;
BEGIN
for v in c loop
update dept set dname = 'aa' where current of c;
commit;
end loop;
END;
BULK COLLECT
BULK COLLECT IN FETCHEx:
DECLARE
Type t is table of dept%rowtype;
nt t;
Cursor c is select *from dept;
BEGIN
Open c;
Fetch c bulk collect into nt;
Close c;
For i in nt.first..nt.last loop
dbms_output.put_line('Dname = ' || nt(i).dname || ' Loc = ' || nt(i).loc);
end loop;
END;
Output:
Dname = ACCOUNTING Loc = NEW YORK
Dname = RESEARCH Loc = DALLAS
Dname = SALES Loc = CHICAGO
Dname = OPERATIONS Loc = BOSTON
BULK COLLECT IN SELECTEx:
DECLARE
Type t is table of dept%rowtype;
Nt t;
BEGIN
Select * bulk collect into nt from dept;
for i in nt.first..nt.last loop
dbms_output.put_line('Dname = ' || nt(i).dname || ' Loc = ' || nt(i).loc);
end loop;
END;
Output:
Dname = ACCOUNTING Loc = NEW YORK
Dname = RESEARCH Loc = DALLAS
Dname = SALES Loc = CHICAGO
Dname = OPERATIONS Loc = BOSTON
LIMIT IN BULK COLLECTYou can use this to limit the number of rows to be fetched.Ex:
DECLARE
Type t is table of dept%rowtype;
nt t;
Cursor c is select *from dept;
BEGIN
Open c;
Fetch c bulk collect into nt limit 2;
Close c;
For i in nt.first..nt.last loop
dbms_output.put_line('Dname = ' || nt(i).dname || ' Loc = ' || nt(i).loc);
MULTIPLE FETCHES IN INTO CLAUSEEx1:
DECLARE
Type t is table of dept.dname%type;
nt t;
Type t1 is table of dept.loc%type;
nt1 t;
Cursor c is select dname,loc from dept;
BEGIN
Open c;
Fetch c bulk collect into nt,nt1;
Close c;
For i in nt.first..nt.last loop
dbms_output.put_line('Dname = ' || nt(i));
end loop;
For i in nt1.first..nt1.last loop
dbms_output.put_line('Loc = ' || nt1(i));
end loop;
END;
Output:
Dname = ACCOUNTING
Dname = RESEARCH
Dname = SALES
Dname = OPERATIONS
Loc = NEW YORK
Loc = DALLAS
Loc = CHICAGO
Loc = BOSTON
Ex2:
DECLARE
type t is table of dept.dname%type;
type t1 is table of dept.loc%type;
nt t;
nt1 t1;
BEGIN
Select dname,loc bulk collect into nt,nt1 from dept;
for i in nt.first..nt.last loop
dbms_output.put_line('Dname = ' || nt(i));
end loop;
for i in nt1.first..nt1.last loop
dbms_output.put_line('Loc = ' || nt1(i));
end loop;
END;
Output:
Dname = ACCOUNTING
Dname = RESEARCH
Dname = SALES
Dname = OPERATIONS
Loc = NEW YORK
Loc = DALLAS
Loc = CHICAGO
Loc = BOSTON
RETURNING CLAUSE IN BULK COLLECTYou can use this to return the processed data to the ouput variables or typed variables.Ex:
DECLARE
type t is table of number(2);
nt t := t(1,2,3,4);
type t1 is table of varchar(2);
nt1 t1;
type t2 is table of student%rowtype;
nt2 t2;
BEGIN
select name bulk collect into nt1 from student;
forall v in nt1.first..nt1.last
update student set no = nt(v) where name = nt1(v) returning
POINTS TO REMEMBER
SQL IN PL/SQLThe only statements allowed directly in pl/sql are DML and TCL.BINDINGBinding a variable is the process of identifying the storage location associated with an identifier in the program. Types of binding
DYNAMIC SQL
USING NATIVE DYNAMIC SQLUSING EXECUTE IMMEDIATEEx:
BEGIN
Execute immediate 'create table student(no number(2),name varchar(10))';
USING EXECUTE IMMEDIATE WITH PL/SQL VARIABLESEx:
DECLARE
v varchar(100);
BEGIN
v := 'create table student(no number(2),name varchar(10))';
execute immediate v;
END;
USING EXECUTE IMMEDIATE WITH BIND VARIABLES AND USING CLAUSEEx:
DECLARE
v varchar(100);
BEGIN
v := 'insert into student values(:v1,:v2,:v3)';
execute immediate v using 6,'f',600;
END;
EXECUTING QUERIES WITH OPEN FOR AND USING CLAUSEEx:
CREATE OR REPLACE PROCEDURE P(smarks in number) IS
s varchar(100) := 'select *from student where marks > :m';
type t is ref cursor;
c t;
v student%rowtype;
BEGIN
open c for s using smarks;
loop
fetch c into v;
exit when c%notfound;
dbms_output.put_line('Student Marks = ' || v.marks);
end loop;
close c;
END;
Output:
SQL> exec p(100)
Student Marks = 200
Student Marks = 300
Student Marks = 400
QUERIES WITH EXECUTE IMMEDIATEEx:
DECLARE
d_name dept.dname%type;
lc dept.loc%type;
v varchar(100);
BEGIN
v := 'select dname from dept where deptno = 10';
execute immediate v into d_name;
dbms_output.put_line('Dname = '|| d_name);
v := 'select loc from dept where dname = :dn';
execute immediate v into lc using d_name;
dbms_output.put_line('Loc = ' || lc);
END;
Output:
Dname = ACCOUNTING
Loc = NEW YORK
VARIABLE NAMES
Ex:
DECLARE
Marks number(3) := 100;
BEGIN
Delete student where marks = marks; -- this will delete all the rows
This can be avoided by using the labeled blocks.
<<my_block>>
DECLARE
Marks number(3) := 100;
BEGIN
Delete student where marks = my_block.marks; -- delete rows which has a
GETTING DATA INTO PL/SQL VARIABLESEx:
DECLARE
V1 number;
V2 varchar(2);
BEGIN
Select no,name into v1,v2 from student where marks = 100;
END;
DML AND RECORDSEx: CREATE OR REPLACE PROCEDURE P(srow in student%rowtype) IS BEGIN insert into student values srow; END P;
DECLARE
s student%rowtype;
BEGIN
s.no := 11;
s.name := 'aa';
s.marks := 100;
p(s);
END;
RECORD BASED INSERTSEx:
DECLARE
srow student%rowtype;
BEGIN
srow.no := 7;
srow.name := 'cc';
srow.marks := 500;
insert into student values srow;
END;
RECORD BASED UPDATESEx:
DECLARE
srow student%rowtype;
BEGIN
srow.no := 6;
srow.name := 'cc';
srow.marks := 500;
update student set row=srow where no = srow.no;
END;
USING RECORDS WITH RETURNING CLAUSEEx:
DECLARE
srow student%rowtype;
sreturn student%rowtype;
BEGIN
srow.no := 8;
srow.name := 'dd';
srow.marks := 500;
insert into student values srow returning no,name,marks into sreturn;
dbms_output.put_line('No = ' || sreturn.no);
dbms_output.put_line('No = ' || sreturn.name);
dbms_output.put_line('No = ' || sreturn.marks);
END;
Output:
No = 8
No = dd
No = 500
FORALL STATEMENTThis can be used to get the data from the database at once by reducting the number of context switches which is a transfer of control between PL/SQL and SQL engine.Syntax:
Forall index_var in
[ Lower_bound..upper_bound |
Indices of indexing_collection |
Values of indexing_collection ]
SQL statement;
FORALL WITH NON-SEQUENTIAL ARRAYSEx:
DECLARE
type t is table of student.no%type index by binary_integer;
ibt t;
BEGIN
ibt(1) := 1;
ibt(10) := 2;
forall i in ibt.first..ibt.last
update student set marks = 900 where no = ibt(i);
END;
The above program will give error like 'element at index [2] does not exists.
You can rectify it in one of the two following ways.
USGAGE OF INDICES OF TO AVOID THE ABOVE BEHAVIOUREx:
DECLARE
type t is table of student.no%type index by binary_integer;
ibt t;
type t1 is table of boolean index by binary_integer;
ibt1 t1;
BEGIN
ibt(1) := 1;
ibt(10) := 2;
ibt(100) := 3;
ibt1(1) := true;
ibt1(10) := true;
ibt1(100) := true;
forall i in indices of ibt1
update student set marks = 900 where no = ibt(i);
END;
USGAGE OF INDICES OF TO AVOID THE ABOVE BEHAVIOUREx:
DECLARE
type t is table of student.no%type index by binary_integer;
ibt t;
type t1 is table of pls_integer index by binary_integer;
ibt1 t1;
BEGIN
ibt(1) := 1;
ibt(10) := 2;
ibt(100) := 3;
ibt1(11) := 1;
ibt1(15) := 10;
ibt1(18) := 100;
forall i in values of ibt1
update student set marks = 567 where no = ibt(i);
END;
POINTS ABOUT BULK BINDS
POINTS ABOUT RETURING CLAUSE
COLLECTIONS
TYPES
VARRAYS
Syntax: Type <TYPE_NAME> is varray | varying array (<LIMIT>) of <ELEMENT_TYPE>; Ex1:
DECLARE
type t is varray(10) of varchar(2);
va t := t('a','b','c','d');
flag boolean;
BEGIN
dbms_output.put_line('Limit = ' || va.limit);
dbms_output.put_line('Count = ' || va.count);
dbms_output.put_line('First Index = ' || va.first);
dbms_output.put_line('Last Index = ' || va.last);
dbms_output.put_line('Next Index = ' || va.next(2));
dbms_output.put_line('Previous Index = ' || va.prior(3));
dbms_output.put_line('VARRAY ELEMENTS');
for i in va.first..va.last loop
dbms_output.put_line('va[' || i || '] = ' || va(i));
end loop;
flag := va.exists(3);
if flag = true then
dbms_output.put_line('Index 3 exists with an element ' || va(3));
else
dbms_output.put_line('Index 3 does not exists');
end if;
va.extend;
dbms_output.put_line('After extend of one index, Count = ' || va.count);
flag := va.exists(5);
if flag = true then
dbms_output.put_line('Index 5 exists with an element ' || va(5));
else
dbms_output.put_line('Index 5 does not exists');
end if;
flag := va.exists(6);
if flag = true then
dbms_output.put_line('Index 6 exists with an element ' || va(6));
else
dbms_output.put_line('Index 6 does not exists');
end if;
va.extend(2);
dbms_output.put_line('After extend of two indexes, Count = ' || va.count);
dbms_output.put_line('VARRAY ELEMENTS');
for i in va.first..va.last loop
dbms_output.put_line('va[' || i || '] = ' || va(i));
end loop;
va(5) := 'e';
va(6) := 'f';
va(7) := 'g';
dbms_output.put_line('AFTER ASSINGNING VALUES TO EXTENDED ELEMENTS,
VARRAY ELEMENTS');
for i in va.first..va.last loop
dbms_output.put_line('va[' || i || '] = ' || va(i));
end loop;
va.extend(3,2);
dbms_output.put_line('After extend of three indexes,
Ex2:
DECLARE
type t is varray(4) of student%rowtype;
va t := t(null,null,null,null);
BEGIN
for i in 1..va.count loop
select * into va(i) from student where sno = i;
dbms_output.put_line('Sno = ' || va(i).sno || ' Sname = ' || va(i).sname);
end loop;
END;
Output:
Sno = 1 Sname = saketh
Sno = 2 Sname = srinu
Sno = 3 Sname = divya
Sno = 4 Sname = manogni
Ex3:
DECLARE
type t is varray(4) of student.smarks%type;
va t := t(null,null,null,null);
BEGIN
for i in 1..va.count loop
select smarks into va(i) from student where sno = i;
dbms_output.put_line('Smarks = ' || va(i));
end loop;
END;
Output:
Smarks = 100
Smarks = 200
Smarks = 300
Smarks = 400
Ex4:
DECLARE
type r is record(c1 student.sname%type,c2 student.smarks%type);
type t is varray(4) of r;
va t := t(null,null,null,null);
BEGIN
for i in 1..va.count loop
select sname,smarks into va(i) from student where sno = i;
dbms_output.put_line('Sname = ' || va(i).c1 || ' Smarks = '
Ex5:
DECLARE
type t is varray(1) of addr;
va t := t(null);
cursor c is select * from employ;
i number := 1;
BEGIN
for v in c loop
select address into va(i) from employ where ename = v.ename;
dbms_output.put_line('Hno = ' || va(i).hno || ' City = '
Ex6:
DECLARE
type t is varray(5) of varchar(2);
va1 t;
va2 t := t();
BEGIN
if va1 is null then
dbms_output.put_line('va1 is null');
else
dbms_output.put_line('va1 is not null');
end if;
if va2 is null then
dbms_output.put_line('va2 is null');
else
dbms_output.put_line('va2 is not null');
end if;
END;
Output:
va1 is null
va2 is not null
NESTED TABLES
Syntax: Type <TYPE_NAME> is table of <TABLE_TYPE>; Ex1:
DECLARE
type t is table of varchar(2);
nt t := t('a','b','c','d');
flag boolean;
BEGIN
if nt.limit is null then
dbms_output.put_line('No limit to Nested Tables');
else
dbms_output.put_line('Limit = ' || nt.limit);
end if;
dbms_output.put_line('Count = ' || nt.count);
dbms_output.put_line('First Index = ' || nt.first);
dbms_output.put_line('Last Index = ' || nt.last);
dbms_output.put_line('Next Index = ' || nt.next(2));
dbms_output.put_line('Previous Index = ' || nt.prior(3));
dbms_output.put_line('NESTED TABLE ELEMENTS');
for i in 1..nt.count loop
dbms_output.put_line('nt[' || i || '] = ' || nt(i));
end loop;
flag := nt.exists(3);
if flag = true then
dbms_output.put_line('Index 3 exists with an element ' || nt(3));
else
dbms_output.put_line('Index 3 does not exists');
end if;
nt.extend;
dbms_output.put_line('After extend of one index, Count = ' || nt.count);
flag := nt.exists(5);
if flag = true then
dbms_output.put_line('Index 5 exists with an element ' || nt(5));
else
dbms_output.put_line('Index 5 does not exists');
end if;
flag := nt.exists(6);
if flag = true then
dbms_output.put_line('Index 6 exists with an element ' || nt(6));
else
dbms_output.put_line('Index 6 does not exists');
end if;
nt.extend(2);
dbms_output.put_line('After extend of two indexes, Count = ' || nt.count);
dbms_output.put_line('NESTED TABLE ELEMENTS');
for i in 1..nt.count loop
dbms_output.put_line('nt[' || i || '] = ' || nt(i));
end loop;
nt(5) := 'e';
nt(6) := 'f';
nt(7) := 'g';
dbms_output.put_line('AFTER ASSINGNING VALUES TO EXTENDED ELEMENTS,
Ex2:
DECLARE
type t is table of student%rowtype;
nt t := t(null,null,null,null);
BEGIN
for i in 1..nt.count loop
select * into nt(i) from student where sno = i;
dbms_output.put_line('Sno = ' || nt(i).sno || ' Sname = ' || nt(i).sname);
end loop;
END;
Output:
Sno = 1 Sname = saketh
Sno = 2 Sname = srinu
Sno = 3 Sname = divya
Sno = 4 Sname = manogni
Ex3:
DECLARE
type t is table of student.smarks%type;
nt t := t(null,null,null,null);
BEGIN
for i in 1..nt.count loop
select smarks into nt(i) from student where sno = i;
dbms_output.put_line('Smarks = ' || nt(i));
end loop;
END;
Output:
Smarks = 100
Smarks = 200
Smarks = 300
Smarks = 400
Ex4:
DECLARE
type r is record(c1 student.sname%type,c2 student.smarks%type);
type t is table of r;
nt t := t(null,null,null,null);
BEGIN
for i in 1..nt.count loop
select sname,smarks into nt(i) from student where sno = i;
dbms_output.put_line('Sname = ' || nt(i).c1 || ' Smarks = ' || nt(i).c2);
end loop;
END;
Output:
Sname = saketh Smarks = 100
Sname = srinu Smarks = 200
Sname = divya Smarks = 300
Sname = manogni Smarks = 400
Ex5:
DECLARE
type t is table of addr;
nt t := t(null);
cursor c is select * from employ;
i number := 1;
BEGIN
for v in c loop
select address into nt(i) from employ where ename = v.ename;
dbms_output.put_line('Hno = ' || nt(i).hno || ' City = ' || nt(i).city);
end loop;
END;
Output:
Hno = 11 City = hyd
Hno = 22 City = bang
Hno = 33 City = kochi
Ex6:
DECLARE
type t is varray(5) of varchar(2);
nt1 t;
nt2 t := t();
BEGIN
if nt1 is null then
dbms_output.put_line('nt1 is null');
else
dbms_output.put_line('nt1 is not null');
end if;
if nt2 is null then
dbms_output.put_line('nt2 is null');
else
dbms_output.put_line('nt2 is not null');
end if;
END;
Output:
nt1 is null
nt2 is not null
INDEX-BY TABLES
Syntax: Type <TYPE_NAME> is table of <TABLE_TYPE> index by binary_integer; Ex:
DECLARE
type t is table of varchar(2) index by binary_integer;
ibt t;
flag boolean;
BEGIN
ibt(1) := 'a';
ibt(-20) := 'b';
ibt(30) := 'c';
ibt(100) := 'd';
if ibt.limit is null then
dbms_output.put_line('No limit to Index by Tables');
else
dbms_output.put_line('Limit = ' || ibt.limit);
end if;
dbms_output.put_line('Count = ' || ibt.count);
dbms_output.put_line('First Index = ' || ibt.first);
dbms_output.put_line('Last Index = ' || ibt.last);
dbms_output.put_line('Next Index = ' || ibt.next(2));
dbms_output.put_line('Previous Index = ' || ibt.prior(3));
dbms_output.put_line('INDEX BY TABLE ELEMENTS');
dbms_output.put_line('ibt[-20] = ' || ibt(-20));
dbms_output.put_line('ibt[1] = ' || ibt(1));
dbms_output.put_line('ibt[30] = ' || ibt(30));
dbms_output.put_line('ibt[100] = ' || ibt(100));
flag := ibt.exists(30);
if flag = true then
dbms_output.put_line('Index 30 exists with an element ' || ibt(30));
else
dbms_output.put_line('Index 30 does not exists');
end if;
flag := ibt.exists(50);
if flag = true then
dbms_output.put_line('Index 50 exists with an element ' || ibt(30));
else
dbms_output.put_line('Index 50 does not exists');
end if;
ibt.delete(1);
dbms_output.put_line('After delete of first index, Count = ' || ibt.count);
ibt.delete(30);
dbms_output.put_line('After delete of index thirty, Count = ' || ibt.count);
dbms_output.put_line('INDEX BY TABLE ELEMENTS');
dbms_output.put_line('ibt[-20] = ' || ibt(-20));
dbms_output.put_line('ibt[100] = ' || ibt(100));
ibt.delete;
dbms_output.put_line('After delete of entire
DIFFERENCES AMONG COLLECTIONS
MULTILEVEL COLLECTIONSCollections of more than one dimension which is a collection of collections, known as multilevel collections.Syntax: Type <TYPE_NAME1> is table of <TABLE_TYPE> index by binary_integer; Type <TYPE_NAME2> is varray(<LIMIT>) | table | of <TYPE_NAME1> | index by binary_integer; Ex1:
DECLARE
type t1 is table of varchar(2) index by binary_integer;
type t2 is varray(5) of t1;
va t2 := t2();
c number := 97;
flag boolean;
BEGIN
va.extend(4);
dbms_output.put_line('Count = ' || va.count);
dbms_output.put_line('Limit = ' || va.limit);
for i in 1..va.count loop
for j in 1..va.count loop
va(i)(j) := chr(c);
c := c + 1;
end loop;
end loop;
dbms_output.put_line('VARRAY ELEMENTS');
for i in 1..va.count loop
for j in 1..va.count loop
dbms_output.put_line('va[' || i || '][' || j || '] = ' || va(i)(j));
end loop;
end loop;
dbms_output.put_line('First index = ' || va.first);
dbms_output.put_line('Last index = ' || va.last);
dbms_output.put_line('Next index = ' || va.next(2));
dbms_output.put_line('Previous index = ' || va.prior(3));
flag := va.exists(2);
if flag = true then
dbms_output.put_line('Index 2 exists');
else
dbms_output.put_line('Index 2 exists');
end if;
va.extend;
va(1)(5) := 'q';
va(2)(5) := 'r';
va(3)(5) := 's';
va(4)(5) := 't';
va(5)(1) := 'u';
va(5)(2) := 'v';
va(5)(3) := 'w';
va(5)(4) := 'x';
va(5)(5) := 'y';
dbms_output.put_line('After extend of one index, Count = ' || va.count);
dbms_output.put_line('VARRAY ELEMENTS');
for i in 1..va.count loop
for j in 1..va.count loop
dbms_output.put_line('va[' || i || '][' || j || '] = ' || va(i)(j));
end loop;
end loop;
va.trim;
dbms_output.put_line('After trim of one index, Count = ' || va.count);
va.trim(2);
dbms_output.put_line('After trim of two indexes, Count = ' || va.count);
dbms_output.put_line('VARRAY ELEMENTS');
for i in 1..va.count loop
for j in 1..va.count loop
dbms_output.put_line('va[' || i || '][' || j || '] = ' || va(i)(j));
Ex2:
DECLARE
type t1 is table of varchar(2) index by binary_integer;
type t2 is table of t1;
nt t2 := t2();
c number := 65;
v number := 1;
flag boolean;
BEGIN
nt.extend(4);
dbms_output.put_line('Count = ' || nt.count);
if nt.limit is null then
dbms_output.put_line('No limit to Nested Tables');
else
dbms_output.put_line('Limit = ' || nt.limit);
end if;
for i in 1..nt.count loop
for j in 1..nt.count loop
nt(i)(j) := chr(c);
c := c + 1;
if c = 91 then
c := 97;
end if;
end loop;
end loop;
dbms_output.put_line('NESTED TABLE ELEMENTS');
for i in 1..nt.count loop
for j in 1..nt.count loop
dbms_output.put_line(
Ex3:
DECLARE
type t1 is table of varchar(2) index by binary_integer;
type t2 is table of t1 index by binary_integer;
ibt t2;
flag boolean;
BEGIN
dbms_output.put_line('Count = ' || ibt.count);
if ibt.limit is null then
dbms_output.put_line('No limit to Index-by Tables');
else
dbms_output.put_line('Limit = ' || ibt.limit);
end if;
ibt(1)(1) := 'a';
ibt(4)(5) := 'b';
ibt(5)(1) := 'c';
ibt(6)(2) := 'd';
ibt(8)(3) := 'e';
ibt(3)(4) := 'f';
dbms_output.put_line('INDEX-BY TABLE ELEMENTS');
dbms_output.put_line('ibt([1][1] = ' || ibt(1)(1));
dbms_output.put_line('ibt([4][5] = ' || ibt(4)(5));
dbms_output.put_line('ibt([5][1] = ' || ibt(5)(1));
dbms_output.put_line('ibt([6][2] = ' || ibt(6)(2));
dbms_output.put_line('ibt([8][3] = ' || ibt(8)(3));
dbms_output.put_line('ibt([3][4] = ' || ibt(3)(4));
dbms_output.put_line('First Index = ' || ibt.first);
dbms_output.put_line('Last Index = ' || ibt.last);
dbms_output.put_line('Next Index = ' || ibt.next(3));
dbms_output.put_line('Prior Index = ' || ibt.prior(8));
ibt(1)(2) := 'g';
ibt(1)(3) := 'h';
ibt(1)(4) := 'i';
ibt(1)(5) := 'k';
ibt(1)(6) := 'l';
ibt(1)(7) := 'm';
ibt(1)(8) := 'n';
dbms_output.put_line('Count = ' || ibt.count);
dbms_output.put_line('INDEX-BY TABLE ELEMENTS');
for i in 1..8 loop
dbms_output.put_line('ibt[1][' || i || '] = ' || ibt(1)(i));
end loop;
dbms_output.put_line('ibt([4][5] = ' || ibt(4)(5));
dbms_output.put_line('ibt([5][1] = ' || ibt(5)(1));
dbms_output.put_line('ibt([6][2] = ' || ibt(6)(2));
dbms_output.put_line('ibt([8][3] = ' || ibt(8)(3));
dbms_output.put_line('ibt([3][4] = ' || ibt(3)(4));
flag := ibt.exists(3);
if flag = true then
dbms_output.put_line('Index 3 exists');
else
dbms_output.put_line('Index 3 exists');
end if;
ibt.delete(1);
dbms_output.put_line('After delete of first index, Count = ' || ibt.count);
ibt.delete(4);
dbms_output.put_line('After delete of fourth index, Count = ' || ibt.count);
dbms_output.put_line('INDEX-BY TABLE ELEMENTS');
dbms_output.put_line('ibt([5][1] = ' || ibt(5)(1));
dbms_output.put_line('ibt([6][2] = ' || ibt(6)(2));
dbms_output.put_line('ibt([8][3] = ' || ibt(8)(3));
dbms_output.put_line('ibt([3][4] = ' || ibt(3)(4));
ibt.delete;
dbms_output.put_line('After delete
Ex4:
DECLARE
type t1 is table of varchar(2) index by binary_integer;
type t2 is table of t1 index by binary_integer;
type t3 is table of t2;
nt t3 := t3();
c number := 65;
BEGIN
nt.extend(2);
dbms_output.put_line('Count = ' || nt.count);
for i in 1..nt.count loop
for j in 1..nt.count loop
for k in 1..nt.count loop
nt(i)(j)(k) := chr(c);
c := c + 1;
end loop;
end loop;
end loop;
dbms_output.put_line('NESTED TABLE ELEMENTS');
for i in 1..nt.count loop
for j in 1..nt.count loop
for k in 1..nt.count loop
dbms_output.put_line(OBJECTS USED IN THE EXAMPLESSQL> select * from student;
SNO SNAME SMARKS
---------- -------------- ----------
1 saketh 100
2 srinu 200
3 divya 300
4 manogni 400
SQL> create or replace type addr as object(hno number(2),city varchar(10));/
SQL> select * from employ; ENAME JOB ADDRESS(HNO, CITY) ---------- ---------- ----------------------------- Ranjit clerk ADDR(11, 'hyd') Satish manager ADDR(22, 'bang') Srinu engineer ADDR(33, 'kochi') ERROR HANDLING
ERROR TYPES
HANDLING EXCEPTIONS
Syntax: EXCEPTION When exception_name then Sequence_of_statements; When exception_name then Sequence_of_statements; When others then Sequence_of_statements; END; EXCEPTION TYPES
PREDEFINED EXCEPTIONS
Ex1:
DECLARE
a number;
b varchar(2);
v_marks number;
cursor c is select * from student;
type t is varray(3) of varchar(2);
va t := t('a','b');
va1 t;
BEGIN
-- NO_DATA_FOUND
BEGIN
select smarks into v_marks from student where sno = 50;
EXCEPTION
when no_data_found then
dbms_output.put_line('Invalid student number');
END;
-- CURSOR_ALREADY_OPEN
BEGIN
open c;
open c;
EXCEPTION
when cursor_already_open then
dbms_output.put_line('Cursor is already opened');
END;
-- INVALID_CURSOR
BEGIN
close c;
open c;
close c;
close c;
EXCEPTION
when invalid_cursor then
dbms_output.put_line('Cursor is already closed');
END;
-- TOO_MANY_ROWS
BEGIN
select smarks into v_marks from student where sno > 1;
EXCEPTION
when too_many_rows then
dbms_output.put_line('Too many values are coming to marks variable');
END;
-- ZERO_DIVIDE
BEGIN
a := 5/0;
EXCEPTION
when zero_divide then
dbms_output.put_line('Divided by zero - invalid operation');
END;
-- VALUE_ERROR
BEGIN
b := 'saketh';
EXCEPTION
when value_error then
dbms_output.put_line('Invalid string length');
END;
-- INVALID_NUMBER
BEGIN
insert into student values('a','srinu',100);
EXCEPTION
when invalid_number then
dbms_output.put_line('Invalid number');
END;
-- SUBSCRIPT_OUTSIDE_LIMIT
BEGIN
va(4) := 'c';
EXCEPTION
when subscript_outside_limit then
dbms_output.put_line('Index is greater than the limit');
END;
-- SUBSCRIPT_BEYOND_COUNT
BEGIN
va(3) := 'c';
EXCEPTION
when subscript_beyond_count then
dbms_output.put_line('Index is greater than the count');
END;
-- COLLECTION_IS_NULL
BEGIN
va1(1) := 'a';
EXCEPTION
when collection_is_null then
dbms_output.put_line('Collection is empty');
END;
--
END;
Output:
Invalid student number
Cursor is already opened
Cursor is already closed
Too many values are coming to marks variable
Divided by zero - invalid operation
Invalid string length
Invalid number
Index is greater than the limit
Index is greater than the count
Collection is empty
Ex2:
DECLARE
c number;
BEGIN
c := 5/0;
EXCEPTION
when zero_divide then
dbms_output.put_line('Invalid Operation');
when others then
dbms_output.put_line('From OTHERS handler: Invalid Operation');
END;
Output:
Invalid Operation
USER-DEFINED EXCEPTIONS
Ex:
DECLARE
e exception;
BEGIN
raise e;
EXCEPTION
when e then
dbms_output.put_line('e is raised');
END;
Output:
e is raised
BULIT-IN ERROR FUNCTIONSSQLCODE AND SQLERRM
Ex1:
DECLARE
e exception;
v_dname varchar(10);
BEGIN
-- USER-DEFINED EXCEPTION
BEGIN
raise e;
EXCEPTION
when e then
dbms_output.put_line(SQLCODE || ' ' || SQLERRM);
END;
-- PREDEFINED EXCEPTION
BEGIN
select dname into v_dname from dept where deptno = 50;
EXCEPTION
when no_data_found then
dbms_output.put_line(SQLCODE || ' ' || SQLERRM);
END;
END;
Output:
1 User-Defined Exception
100 ORA-01403: no data found
Ex2:
BEGIN
dbms_output.put_line(SQLERRM(100));
dbms_output.put_line(SQLERRM(0));
dbms_output.put_line(SQLERRM(1));
dbms_output.put_line(SQLERRM(-100));
dbms_output.put_line(SQLERRM(-500));
dbms_output.put_line(SQLERRM(200));
dbms_output.put_line(SQLERRM(-900));
END;
Output:
ORA-01403: no data found
ORA-0000: normal, successful completion
User-Defined Exception
ORA-00100: no data found
ORA-00500: Message 500 not found; product=RDBMS; facility=ORA
-200: non-ORACLE exception
ORA-00900: invalid SQL statement
DBMS_UTILITY.FORMAT_ERROR_STACKThe built-in function, like SQLERRM, returns the message associated with the current error.It differs from SQLERRM in two ways: Its length is not restricted; it will return the full error message string. You can not pass an error code number to this function; it cannot be used to return the message for a random error code. Ex:
DECLARE
v number := 'ab';
BEGIN
null;
EXCEPTION
when others then
dbms_output.put_line(dbms_utility.format_error_stack);
END;
Output:
declare
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 2
DBMS_UTILITY.FORMAT_CALL_STACK
Ex:
BEGIN
dbms_output.put_line(dbms_utility.format_call_stack);
END;
Output:
----- PL/SQL Call Stack -----
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE
Ex:
CREATE OR REPLACE PROCEDURE P1 IS
BEGIN
dbms_output.put_line('from procedure 1');
raise value_error;
END P1;
CREATE OR REPLACE PROCEDURE P2 IS
BEGIN
dbms_output.put_line('from procedure 2');
p1;
END P2;
CREATE OR REPLACE PROCEDURE P3 IS
BEGIN
dbms_output.put_line('from procedure 3');
p2;
EXCEPTION
when others then
dbms_output.put_line(dbms_utility.format_error_backtrace);
END P3;
Output: SQL> exec p3 from procedure 3 from procedure 2 from procedure 1 ORA-06512: at "SAKETH.P1", line 4 ORA-06512: at "SAKETH.P2", line 4 ORA-06512: at "SAKETH.P3", line 4 EXCEPTION_INIT PRAGMA
Syntax: PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number); Ex:
DECLARE
e exception;
pragma exception_init(e,-1476);
c number;
BEGIN
c := 5/0;
EXCEPTION
when e then
dbms_output.put_line('Invalid Operation');
END;
Output:
Invalid Operation
RAISE_APPLICATION_ERRORYou can use this built-in function to create your own error messages, which can be more descriptive than named exceptions.Syntax: RAISE_APPLICATION_ERROR(error_number, error_message,, [keep_errors_flag]);
Ex:
DECLARE
c number;
BEGIN
c := 5/0;
EXCEPTION
when zero_divide then
raise_application_error(-20222,'Invalid Operation');
END;
Output:
DECLARE
*
ERROR at line 1:
ORA-20222: Invalid Operation
ORA-06512: at line 7
EXCEPTION PROPAGATION Exceptions can occur in the declarative, the executable, or the exception section of a PL/SQL block. EXCEPTION RAISED IN THE EXECUATABLE SECTION Exceptions raised in execuatable section can be handled in current block or outer block. Ex1:
DECLARE
e exception;
BEGIN
BEGIN
raise e;
END;
EXCEPTION
when e then
dbms_output.put_line('e is raised');
END;
Output:
e is raised
Ex2:
DECLARE
e exception;
BEGIN
BEGIN
raise e;
END;
END;
Output:
ERROR at line 1:
ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at line 5
EXCEPTION RAISED IN THE DECLARATIVE SECTIONExceptions raised in the declarative secion must be handled in the outer block.Ex1:
DECLARE
c number(3) := 'abcd';
BEGIN
dbms_output.put_line('Hello');
EXCEPTION
when others then
dbms_output.put_line('Invalid string length');
END;
Output:
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 2
Ex2:
BEGIN
DECLARE
c number(3) := 'abcd';
BEGIN
dbms_output.put_line('Hello');
EXCEPTION
when others then
dbms_output.put_line('Invalid string length');
END;
EXCEPTION
when others then
dbms_output.put_line('From outer block: Invalid string length');
END;
Output:
From outer block: Invalid string length
EXCEPTION RAISED IN THE EXCEPTION SECTIONExceptions raised in the declarative secion must be handled in the outer block.Ex1:
DECLARE
e1 exception;
e2 exception;
BEGIN
raise e1;
EXCEPTION
when e1 then
dbms_output.put_line('e1 is raised');
raise e2;
when e2 then
dbms_output.put_line('e2 is raised');
END;
Output:
e1 is raised
DECLARE
*
ERROR at line 1:
ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at line 9
ORA-06510: PL/SQL: unhandled user-defined exception
Ex2:
DECLARE
e1 exception;
e2 exception;
BEGIN
BEGIN
raise e1;
EXCEPTION
when e1 then
dbms_output.put_line('e1 is raised');
raise e2;
when e2 then
dbms_output.put_line('e2 is raised');
END;
EXCEPTION
when e2 then
dbms_output.put_line('From outer block: e2 is raised');
END;
Output:
e1 is raised
From outer block: e2 is raised
Ex3:
DECLARE
e exception;
BEGIN
raise e;
EXCEPTION
when e then
dbms_output.put_line('e is raised');
raise e;
END;
Output:
e is raised
DECLARE
*
ERROR at line 1:
ORA-06510: PL/SQL: unhandled user-defined exception
ORA-06512: at line 8
ORA-06510: PL/SQL: unhandled user-defined exception
RESTRICTIONSYou can not pass exception as an argument to a subprogram.DATABASE TRIGGERS
RESTRICTIONS ON TRIGGERES
USE OF TRIGGERS
TYPES OF TRIGGERS
CATEGORIESTiming -- Before or AfterLevel -- Row or Statement
DML TRIGGER SYNTAXCreate or replace trigger <trigger_name> Before | after on insert or update or delete [For each row] Begin -- trigger body End <trigger_name>; DML TRIGGERS
ORDER OF DML TRIGGER FIRING
Suppose we have a follwing table. SQL> select * from student;
NO NAME MARKS
----- ------- ----------
1 a 100
2 b 200
3 c 300
4 d 400
Also we have triggering_firing_order table with firing_order as the field.
CREATE OR REPLACE TRIGGER TRIGGER1
before insert on student
BEGIN
insert into trigger_firing_order values('Before Statement Level');
END TRIGGER1;
CREATE OR REPLACE TRIGGER TRIGGER2
before insert on student
for each row
BEGIN
insert into trigger_firing_order values('Before Row Level');
END TRIGGER2;
CREATE OR REPLACE TRIGGER TRIGGER3
after insert on student
BEGIN
insert into trigger_firing_order values('After Statement Level');
END TRIGGER3;
CREATE OR REPLACE TRIGGER TRIGGER4
after insert on student
for each row
BEGIN
insert into trigger_firing_order values('After Row Level');
END TRIGGER4;
Output:
SQL> select * from trigger_firing_order;
no rows selected
SQL> insert into student values(5,'e',500);
1 row created.
SQL> select * from trigger_firing_order;
FIRING_ORDER
--------------------------------------------------
Before Statement Level
Before Row Level
After Row Level
After Statement Level
SQL> select * from student;
NO NAME MARKS
---- -------- ----------
1 a 100
2 b 200
3 c 300
4 d 400
5 e 500
CORRELATION IDENTIFIERS IN ROW-LEVEL TRIGGERS
TRIGGERING STATEMENT :OLD :NEW
-------------------- ---------------------- --------------------------
INSERT all fields are NULL. values that will be inserted
When the statement is completed.
UPDATE original values for new values that will be updated
the row before the when the statement is completed.
update.
DELETE original values before all fields are NULL.
the row is deleted.
Ex: Suppose we have a table called marks with fields no, old_marks, new_marks.
CREATE OR REPLACE TRIGGER OLD_NEW
before insert or update or delete on student
for each row
BEGIN
insert into marks values(:old.no,:old.marks,:new.marks);
END OLD_NEW;
Output:
SQL> select * from student;
NO NAME MARKS
---- ------- -------
1 a 100
2 b 200
3 c 300
4 d 400
5 e 500
SQL> select * from marks;
no rows selected SQL> insert into student values(6,'f',600); 1 row created. SQL> select * from student;
NO NAME MARKS
---- ------ -------
1 a 100
2 b 200
3 c 300
4 d 400
5 e 500
6 f 600
SQL> select * from marks;
NO OLD_MARKS NEW_MARKS
---- -------- ---------
600
SQL> update student set marks=555 where no=5;
1 row updated. SQL> select * from student;
NO NAME MARKS
----- ------- -------
1 a 100
2 b 200
3 c 300
4 d 400
5 e 555
6 f 600
SQL> select * from marks;
NO OLD_MARKS NEW_MARKS
---- ---------- -----------
600
5 500 555
SQL> delete student where no = 2; 1 row deleted. SQL> select * from student;
NO NAME MARKS
---- ------ ----------
1 a 100
3 c 300
4 d 400
5 e 555
6 f 600
SQL> select * from marks;
NO OLD_MARKS NEW_MARKS
---- ---------- ----------------
600
5 500 555
2 200
REFERENCING CLAUSEIf desired, you can use the REFERENCING clause to specify a different name for :old ane :new.This clause is found after the triggering event, before the WHEN clause. Syntax: REFERENCING [old as old_name] [new as new_name] Ex:
CREATE OR REPLACE TRIGGER REFERENCE_TRIGGER
before insert or update or delete on student
referencing old as old_student new as new_student
for each row
BEGIN
insert into marks
values(:old_student.no,:old_student.marks,:new_student.marks);
END REFERENCE_TRIGGER;
WHEN CLAUSEWHEN clause is valid for row-level triggers only.If present, the trigger body will be executed only for those rows that meet the condition specified by the WHEN clause. Syntax: WHEN trigger_condition; Where trigger_condition is a Boolean expression. It will be evaluated for each row. The :new and :old records can be referenced inside trigger_condition as well, but like REFERENCING, the colon is not used there. The colon is only valid in the trigger body. Ex:
CREATE OR REPLACE TRIGGER WHEN_TRIGGER
before insert or update or delete on student
referencing old as old_student new as new_student
for each row
when (new_student.marks > 500)
BEGIN
insert into marks
values(:old_student.no,:old_student.marks,:new_student.marks);
END WHEN_TRIGGER;
TRIGGER PREDICATESThere are three Boolean functions that you can use to determine what the operation is.The predicates are
CREATE OR REPLACE TRIGGER PREDICATE_TRIGGER
before insert or update or delete on student
BEGIN
if inserting then
insert into predicates values('I');
elsif updating then
insert into predicates values('U');
elsif deleting then
insert into predicates values('D');
end if;
END PREDICATE_TRIGGER;
Output:
SQL> delete student where no=1;
1 row deleted.
SQL> select * from predicates;
MSG
---------------
D
SQL> insert into student values(7,'g',700);
1 row created.
SQL> select * from predicates;
MSG
---------------
D
I
SQL> update student set marks = 777 where no=7;
1 row updated.
SQL> select * from predicates;
MSG
---------------
D
I
U
INSTEAD-OF TRIGGERSInstead-of triggers fire instead of a DML operation.Also, instead-of triggers can be defined only on views. Instead-of triggers are used in two cases:
|