You are on page 1of 182

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

jobs4timesLogo

JOBS4TIMES
INTRODUCTION
SQLisdividedintothefollowing
DataDefinitionLanguage(DDL)
DataManipulationLanguage(DML)
DataRetrievalLanguage(DRL)
TransactionControlLanguage(TCL)
DataControlLanguage(DCL)
DDLcreate,alter,drop,truncate,rename
DMLinsert,update,delete
DRLselect
TCLcommit,rollback,savepoint
DCLgrant,revoke
CREATETABLE
SYNTAX:
Createtable<table_name>(col1datatype1,col2datatype2...colndatatypen)
Ex:
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3))
INSERT
Thiswillbeusedtoinserttherecordsintotable.
Wehavetwomethodstoinsert.
Byvaluemethod
Byaddressmethod
a. USINGVALUEMETHOD
Syntax:
insertinto<table_name>values(value1,value2,value3....Valuen)
Ex:
SQL>insertintostudentvalues(1,'sudha',100)
SQL>insertintostudentvalues(2,'saketh',200)
Toinsertanewrecordagainyouhavetotypeentireinsertcommand,iftherearelotofrecordsthiswillbe
difficult.
Thiswillbeavoidedbyusingaddressmethod.
b. USINGADDRESSMETHOD
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

1/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Syntax:
insertinto<table_name>values(&col1,&col2,&col3....&coln)
Thiswillpromptyouforthevaluesbutforeveryinsertyouhavetouseforwardslash.
Ex:
SQL>insertintostudentvalues(&no,'&name',&marks)
Enter value for no: 1
Enter value for name: Jagan
Enter value for marks: 300
old 1: insert into student values(&no, '&name', &marks)
new 1: insert into student values(1, 'Jagan', 300)

SQL>/
Enter value for no: 2
Enter value for name: Naren
Enter value for marks: 400
old 1: insert into student values(&amp;no, '&name', &marks)
new 1: insert into student values(2, 'Naren', 400)

c. INSERTINGDATAINTOSPECIFIEDCOLUMNSUSINGVALUEMETHOD
Syntax:
insertinto<table_name>(col1,col2,col3...Coln)values(value1,value2,value3....Valuen)
Ex:
SQL>insertintostudent(no,name)values(3,'Ramesh')
SQL>insertintostudent(no,name)values(4,'Madhu')
d. INSERTINGDATAINTOSPECIFIEDCOLUMNSUSINGADDRESSMETHOD
Syntax:
insertinto<table_name>(col1,col2,col3...coln)values(&col1,&col2,&col3....&coln)
Thiswillpromptyouforthevaluesbutforeveryinsertyouhavetouseforwardslash.
Ex:
SQL>insertintostudent(no,name)values(&no,'&name')
Enter value for no: 5
Enter value for name: Visu
old 1: insert into student (no, name) values(&no, '&name')
new 1: insert into student (no, name) values(5, 'Visu')

SQL>/
Enter value for no: 6
Enter value for name: Rattu
old 1: insert into student (no, name) values(&no, '&name')
new 1: insert into student (no, name) values(6, 'Rattu')

SELECTINGDATA
Syntax:
Select*from<table_name>here*indicatesallcolumns
or
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

2/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Selectcol1,col2,...colnfrom<table_name>
Ex:
SQL>select*fromstudent
NO NAME
--- -----1 Sudha
2 Saketh
1 Jagan
2 Naren
3 Ramesh
4 Madhu
5 Visu
6 Rattu

MARKS
-------100
200
300
400

SQL>selectno,name,marksfromstudent
NO NAME
--- -----1 Sudha
2 Saketh
1 Jagan
2 Naren
3 Ramesh
4 Madhu
5 Visu
6 Rattu

MARKS
-------100
200
300
400

SQL>selectno,namefromstudent
NO
--1
2
1
2
3
4
5
6

NAME
------Sudha
Saketh
Jagan
Naren
Ramesh
Madhu
Visu
Rattu

CONDITIONALSELECTIONSANDOPERATORS
Wehavetwoclausesusedinthis
Where
Orderby
USINGWHERE
Syntax:
select*from<table_name>where<condition>
thefollowingarethedifferenttypesofoperatorsusedinwhereclause.
Arithmeticoperators
Comparisonoperators
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

3 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Logicaloperators
Arithmeticoperatorshighestprecedence+,,*,/
Comparisonoperators=,!=,>,<,>=,<=,<>
between,notbetween
in,notin
null,notnull
like
Logicaloperators
And
Orlowestprecedence
not
a. USING=,>,<,>=,<=,!=,<>
Ex:
SQL>select*fromstudentwhereno=2
NO NAME
--- ------2 Saketh
2 Naren

MARKS
--------200
400

SQL>select*fromstudentwhereno<2
NO NAME
--- ------1 Sudha
1 Jagan

MARKS
---------100
300

SQL>select*fromstudentwhereno>2
NO NAME
--- ------3 Ramesh
4 Madhu
5 Visu
6 Rattu

MARKS
----------

SQL>select*fromstudentwhereno<=2
NO NAME
--- ------1 Sudha
2 Saketh
1 Jagan
2 Naren

MARKS
---------100
200
300
400

SQL>select*fromstudentwhereno>=2
NO NAME
--- ------2 Saketh
2 Naren
3 Ramesh
4 Madhu
5 Visu
6 Rattu
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

MARKS
--------200
400

4/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>select*fromstudentwhereno!=2
NO NAME
--- ------1 Sudha
1 Jagan
3 Ramesh
4 Madhu
5 Visu
6 Rattu

MARKS
---------100
300

SQL>select*fromstudentwhereno<>2
NO NAME
--- ------1 Sudha
1 Jagan
3 Ramesh
4 Madhu
5 Visu
6 Rattu

MARKS
---------100
300

b. USINGAND
Thiswillgivestheoutputwhenalltheconditionsbecometrue.
Syntax:
select*from<table_name>where<condition1>and<condition2>and..<conditionn>
Ex:
SQL>select*fromstudentwhereno=2andmarks>=200
NO NAME
-------200
400

--- ------2 Saketh


2 Naren

MARKS

c. USINGOR
Thiswillgivestheoutputwheneitheroftheconditionsbecometrue.
Syntax:
select*from<table_name>where<condition1>and<condition2>or..<conditionn>
Ex:
SQL>select*fromstudentwhereno=2ormarks>=200
NO NAME
--- ------2 Saketh
1 Jagan
2 Naren

MARKS
--------200
300
400

d. USINGBETWEEN
Thiswillgivestheoutputbasedonthecolumnanditslowerbound,upperbound.
Syntax:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

5 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

select*from<table_name>where<col>between<lowerbound>and<upperbound>
Ex:
SQL>select*fromstudentwheremarksbetween200and400
NO NAME
--- ------2 Saketh
1 Jagan
2 Naren

MARKS
--------200
300
400

e. USINGNOTBETWEEN
Thiswillgivestheoutputbasedonthecolumnwhichvaluesarenotinitslowerbound,upperbound.
Syntax:
select*from<table_name>where<col>notbetween<lowerbound>and<upperbound>
Ex:
SQL>select*fromstudentwheremarksnotbetween200and400
NO NAME
--- ------1 Sudha

MARKS
--------100

f. USINGIN
Thiswillgivestheoutputbasedonthecolumnanditslistofvaluesspecified.
Syntax:
select*from<table_name>where<col>in(value1,value2,value3...valuen)
Ex:
SQL>select*fromstudentwherenoin(1,2,3)
NO NAME
--- ------1 Sudha
2 Saketh
1 Jagan
2 Naren
3 Ramesh

MARKS
--------100
200
300
400

g. USINGNOTIN
Thiswillgivestheoutputbasedonthecolumnwhichvaluesarenotinthelistofvaluesspecified.
Syntax:
select*from<table_name>where<col>notin(value1,value2,value3...valuen)
Ex:
SQL>select*fromstudentwherenonotin(1,2,3)
NO NAME
--- ------4 Madhu

MARKS
---------

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

6/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

5
6

Visu
Rattu

h. USINGNULL
Thiswillgivestheoutputbasedonthenullvaluesinthespecifiedcolumn.
Syntax:
select*from<table_name>where<col>isnull
Ex:
SQL>select*fromstudentwheremarksisnull
NO NAME
--- ------3 Ramesh
4 Madhu
5 Visu
6 Rattu

MARKS
---------

i. USINGNOTNULL
Thiswillgivestheoutputbasedonthenotnullvaluesinthespecifiedcolumn.
Syntax:
select*from<table_name>where<col>isnotnull
Ex:
SQL>select*fromstudentwheremarksisnotnull
NO NAME
--- ------1 Sudha
2 Saketh
1 Jagan
2 Naren

MARKS
--------100
200
300
400

j. USINGLIKE
Thiswillbeusedtosearchthroughtherowsofdatabasecolumnbasedonthepatternyouspecify.
Syntax:
select*from<table_name>where<col>like<pattern>
Ex:
i. Thiswillgivetherowswhosemarksare100.
SQL>select*fromstudentwheremarkslike100
NO NAME
--- ------1 Sudha

MARKS
--------100

ii. Thiswillgivetherowswhosenamestartwith'S'.
SQL>select*fromstudentwherenamelike'S%'
NO NAME
--- ------1 Sudha
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

MARKS
--------100
7/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Saketh

200

iii. Thiswillgivetherowswhosenameendswith'h'.
SQL>select*fromstudentwherenamelike'%h'
NO NAME
--- ------2 Saketh
3 Ramesh

MARKS
--------200

iv. Thiswillgivetherowswhosename'ssecondletterstartwith'a'.
SQL>select*fromstudentwherenamelike'_a%'
NO NAME
--- ------2 Saketh
1 Jagan
2 Naren
3 Ramesh
4 Madhu
6 Rattu

MARKS
-------200
300
400

v. Thiswillgivetherowswhosename'sthirdletterstartwith'd'.
SQL>select*fromstudentwherenamelike'__d%'
NO NAME
--- ------1 Sudha
4 Madhu

MARKS
--------100

vi. Thiswillgivetherowswhosename'ssecondletterstartwith't'fromending.
SQL>select*fromstudentwherenamelike'%_t%'
NO NAME
--- ------2 Saketh
6 Rattu

MARKS
--------200

vii. Thiswillgivetherowswhosename'sthirdletterstartwith'e'fromending.
SQL>select*fromstudentwherenamelike'%e__%'
NO NAME
--- ----2 Saketh
3 Ramesh

MARKS
--------200

viii. Thiswillgivetherowswhosenamecotains2a's.
SQL>select*fromstudentwherenamelike'%a%a%'
NO NAME
--- ------1 Jagan

MARKS
---------300

*Youhavetospecifythepatternsinlikeusingunderscore(_).
USINGORDERBY
Thiswillbeusedtoorderingthecolumnsdata(ascendingordescending).
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

8 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Syntax:
Select*from<table_name>orderby<col>desc
Bydefaultoraclewilluseascendingorder.Ifyouwantoutputindescendingorderyouhavetousedesc
keywordafterthecolumn.
Ex:
SQL>select*fromstudentorderbyno
NO
--1
1
2
2
3
4
5
6

NAME
------Sudha
Jagan
Saketh
Naren
Ramesh
Madhu
Visu
Rattu

MARKS
--------100
300
200
400

SQL>select*fromstudentorderbynodesc
NO NAME
--- ------6 Rattu
5 Visu
4 Madhu
3 Ramesh
2 Saketh
2 Naren
1 Sudha
1 Jagan

MARKS
---------

200
400
100
300

USINGDML
USINGUPDATE
Thiscanbeusedtomodifythetabledata.
Syntax:
Update<table_name>set<col1>=value1,<col2>=value2where<condition>
Ex:
SQL>updatestudentsetmarks=500
Ifyouarenotspecifyinganyconditionthiswillupdateentiretable.
SQL>updatestudentsetmarks=500whereno=2
SQL>updatestudentsetmarks=500,name='Venu'whereno=1
USINGDELETE
Thiscanbeusedtodeletethetabledatatemporarily.
Syntax:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

9/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Delete<table_name>where<condition>
Ex:
SQL>deletestudent
Ifyouarenotspecifyinganyconditionthiswilldeleteentiretable.
SQL>deletestudentwhereno=2
USINGDDL
USINGALTER
Thiscanbeusedtoaddorremovecolumnsandtomodifytheprecisionofthedatatype.
a. ADDINGCOLUMN
Syntax:
altertable<table_name>add<coldatatype>
Ex:
SQL>altertablestudentaddsdobdate
b. REMOVINGCOLUMN
Syntax:
altertable<table_name>drop<coldatatype>
Ex:
SQL>altertablestudentdropcolumnsdob
c. INCREASINGORDECREASINGPRECISIONOFACOLUMN
Syntax:
altertable<table_name>modify<coldatatype>
Ex:
SQL>altertablestudentmodifymarksnumber(5)
*Todecreaseprecisionthecolumnshouldbeempty.
d. MAKINGCOLUMNUNUSED
Syntax:
altertable<table_name>setunusedcolumn<col>
Ex:
SQL>altertablestudentsetunusedcolumnmarks
Eventhoughthecolumnisunusedstillitwilloccupymemory.
e. DROPPINGUNUSEDCOLUMNS
Syntax:
altertable<table_name>dropunusedcolumns
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

10/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Ex:
SQL>altertablestudentdropunusedcolumns
*Youcannotdropindividualunusedcolumnsofatable.
f. RENAMINGCOLUMN
Syntax:
altertable<table_name>renamecolumn<old_col_name>to<new_col_name>
Ex:
SQL>altertablestudentrenamecolumnmarkstosmarks
USINGTRUNCATE
Thiscanbeusedtodeletetheentiretabledatapermanently.
Syntax:
truncatetable<table_name>
Ex:
SQL>truncatetablestudent
USINGDROP
Thiswillbeusedtodropthedatabaseobject
Syntax:
Droptable<table_name>
Ex:
SQL>droptablestudent
USINGRENAME
Thiswillbeusedtorenamethedatabaseobject
Syntax:
rename<old_table_name>to<new_table_name>
Ex:
SQL>renamestudenttostud
USINGTCL
USINGCOMMIT
Thiswillbeusedtosavethework.
Commitisoftwotypes.
Implicit
Explicit
a. IMPLICIT
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

11/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Thiswillbeissuedbyoracleinternallyintwosituations.
WhenanyDDLoperationisperformed.
WhenyouareexitingfromSQL*PLUS.
b. EXPLICIT
Thiswillbeissuedbytheuser.
Syntax:
Commitorcommitwork
*Wheneveryoucommittedthenthetransactionwascompleted.
USINGROLLBACK
Thiswillundotheoperation.
Thiswillbeappliedintwomethods.
Uptopreviouscommit
Uptopreviousrollback
Syntax:
Rollorrollwork
Or
Rollbackorrollbackwork
*Whileprocessisgoingon,ifsuddenlypowergoesthenoraclewillrollbackthetransaction.
USINGSAVEPOINT
Youcanusesavepointstorollbackportionsofyourcurrentsetoftransactions.
Syntax:
Savepoint<savepoint_name>
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);

Beforerollback
SQL>select*fromstudent
NO NAME
MARKS
--- ---------------1
a
100
2
b
200
3
c
300
4
d
400
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

12/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>rollbacktosavepoints3
Or
SQL>rollbacktos3
Thiswillrollbacklasttworecords.
SQL>select*fromstudent
NO NAME
MARKS
--- ---------------1
a
100
2
b
200

USINGDCL
DCLcommandsareusedtograntingandrevokingthepermissions.
USINGGRANT
Thisisusedtogranttheprivilegestootherusers.
Syntax:
Grant<privileges>on<object_name>to<user_name>[withgrantoption]
Ex:
SQL>grantselectonstudenttosudhayoucangiveindividualprivilege
SQL>grantselect,insertonstudenttosudhayoucangivesetofprivileges
SQL>grantallonstudenttosudhayoucangiveallprivileges
Thesudhauserhastousedotmethodtoaccesstheobject.
SQL>select*fromsaketh.student
Thesudhausercannotgrantpermissiononstudenttabletootherusers.Togetthistypeofoptionusethe
following.
SQL>grantallonstudenttosudhawithgrantoption
Nowsudhauseralsograntpermissionsonstudenttable.
USINGREVOKE
Thisisusedtorevoketheprivilegesfromtheuserstowhichyougrantedtheprivileges.
Syntax:
Revoke<privileges>on<object_name>from<user_name>
Ex:
SQL>revokeselectonstudentformsudhayoucanrevokeindividualprivilege
SQL>revokeselect,insertonstudentfromsudhayoucanrevokesetofprivileges
SQL>revokeallonstudentfromsudhayoucanrevokeallprivileges
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

13 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

USINGALIASES
CREATEWITHSELECT
Wecancreateatableusingexistingtable[alongwithdata].
Syntax:
Createtable<new_table_name>[col1,col2,col3...coln]asselect*from<old_table_name>
Ex:
SQL>createtablestudent1asselect*fromstudent
Creatingtablewithyourowncolumnnames.
SQL>createtablestudent2(sno,sname,smarks)asselect*fromstudent
Creatingtablewithspecifiedcolumns.
SQL>createtablestudent3asselectno,namefromstudent
Creatingtablewithouttabledata.
SQL>createtablestudent2(sno,sname,smarks)asselect*fromstudentwhere1=2
Intheabovewhereclausegiveanyconditionwhichdoesnotsatisfy.
INSERTWITHSELECT
Usingthiswecaninsertexistingtabledatatoaanothertableinasingletrip.Butthetablestructureshouldbe
same.
Syntax:
Insertinto<table1>select*from<table2>
Ex:
SQL>insertintostudent1select*fromstudent
Insertingdataintospecifiedcolumns
SQL>insertintostudent1(no,name)selectno,namefromstudent
COLUMNALIASES
Syntax:
Select<orginal_col><alias_name>from<table_name>
Ex:
SQL>selectnosnofromstudentor
SQL>selectno"sno"fromstudent
TABLEALIASES
Ifyouareusingtablealiasesyoucanusedotmethodtothecolumns.
Syntax:
Select<alias_name>.<col1>,<alias_name>.<col2>...<alias_name>.<coln>from<table_name>
<alias_name>
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

14/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Ex:
SQL>selects.no,s.namefromstudents
USINGMERGE
MERGE
Youcanusemergecommandtoperforminsertandupdateinasinglecommand.
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);

Intheabovethetwotablesarewiththesamestructurebutwecanmergedifferentstructuredtablesalsobut
thedatatypeofthecolumnsshouldmatch.
Assumethatstudent1hascolumnslikeno,name,marksandstudent2hascolumnslikeno,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);

MULTIBLEINSERTS
WehavetablecalledDEPTwiththefollowingcolumnsanddata
DEPTNO DNAME
-------10
20
30
40

LOC
-------accounting
research
sales
operations

---new york
dallas
Chicago
boston

A. CREATESTUDENTTABLE
SQL>Createtablestudent(nonumber(2),namevarchar(2),marksnumber(3))
B. MULTIINSERTWITHALLFIELDS
SQL> Insert all
Into student values(1,'a',100)
Into student values(2,'b',200)
Into student values(3,'c',300)
Select *from dept where deptno=10;

Thisinserts3rows
C. MULTIINSERTWITHSPECIFIEDFIELDS
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

15 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL> insert all


Into student (no,name) values(4,'d')
Into student(name,marks) values('e',400)
Into student values(3,'c',300)
Select *from dept where deptno=10;

Thisinserts3rows
D. MULTIINSERTWITHDUPLICATEROWS
SQL> insert all
Into student values(1,'a',100)
Into student values(2,'b',200)
Into student values(3,'c',300)
Select *from dept where deptno > 10;

Thisinserts9rowsbecauseintheselectstatementretrieves3records(3insertsforeachrowretrieved)
E. MULTIINSERTWITHCONDITIONSBASED
SQL> Insert all
When deptno > 10 then
Into student1 values(1,'a',100)
When dname = 'SALES' then
Into student2 values(2,'b',200)
When loc = 'NEW YORK' then
Into student3 values(3,'c',300)
Select *from dept where deptno>10;

Thisinserts4rowsbecausethefirstconditionsatisfied3times,secondconditionsatisfiedonceandthe
lastnone.
F. MULTIINSERTWITHCONDITIONSBASEDANDELSE
SQL> Insert all
When deptno > 100 then
Into student1 values(1,'a',100)
When dname = 'S' then
Into student2 values(2,'b',200)
When loc = 'NEW YORK' then
Into student3 values(3,'c',300)
Else
Into student values(4,'d',400)
Select *from dept where deptno>10;

Thisinserts3recordsbecausetheelsesatisfied3times
G. MULTIINSERTWITHCONDITIONSBASEDANDFIRST
SQL> Insert first
When deptno = 20 then
Into student1 values(1,'a',100)
When dname = 'RESEARCH' then
Into student2 values(2,'b',200)
When loc = 'NEW YORK' then
Into student3 values(3,'c',300)
Select *from dept where deptno=20;

Thisinserts1recordbecausethefirstclauseavoidtochecktheremainingconditionsoncethecondition
issatisfied.
H. MULTIINSERTWITHCONDITIONSBASED,FIRSTANDELSE
SQL> Insert first
When deptno = 30 then
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

16/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Into student1 values(1,'a',100)


When dname = 'R' then
Into student2 values(2,'b',200)
When loc = 'NEW YORK' then
Into student3 values(3,'c',300)
Else
Into student values(4,'d',400)
Select *from dept where deptno=20;

Thisinserts1recordbecausetheelseclausesatisfiedonce
I. MULTIINSERTWITHMULTIBLETABLES
SQL> Insert all
Into student1 values(1,'a',100)
Into student2 values(2,'b',200)
Into student3 values(3,'c',300)
Select *from dept where deptno=10;

Thisinserts3rows
**Youcanusemultitableswithspecifiedfields,withduplicaterows,withconditions,withfirstandelse
clauses.
FUNCTIONS
Functionscanbecategorizedasfollows.
Singlerowfunctions
Groupfunctions
SINGLEROWFUNCTIONS
Singlerowfunctionscanbecategorizedintofive.
Thesewillbeappliedforeachrowandproducesindividualoutputforeachrow.
Numericfunctions
Stringfunctions
Datefunctions
Miscellaneousfunctions
Conversionfunctions
NUMERICFUNCTIONS
Abs
Sign
Sqrt
Mod
Nvl
Power
Exp
Ln
Log
Ceil
Floor
Round
Trunk
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

17/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Bitand
Greatest
Least
Coalesce
A. ABS
Absolutevalueisthemeasureofthemagnitudeofvalue.Absolutevalueisalwaysapositivenumber.
Syntax:
abs(value)
Ex:
SQL>selectabs(5),abs(5),abs(0),abs(null)fromdual
ABS(5)
-----5

ABS(-5)
-------5

ABS(0) ABS(NULL)
------ --------0

B. SIGN
Signgivesthesignofavalue.
Syntax:
sign(value)
Ex:
SQL>selectsign(5),sign(5),sign(0),sign(null)fromdual
SIGN(5)
------1

SIGN(-5)
--------1

SIGN(0) SIGN(NULL)
------- ---------0

C. SQRT
Thiswillgivethesquarerootofthegivenvalue.
Syntax:
sqrt(value)herevaluemustbepositive.
Ex:
SQL>selectsqrt(4),sqrt(0),sqrt(null),sqrt(1)fromdual
SQRT(4)
------2

SQRT(0) SQRT(NULL)
------- ---------0

SQRT(1)
---------1

D. MOD
Thiswillgivetheremainder.
Syntax:
mod(value,divisor)
Ex:
SQL>selectmod(7,4),mod(1,5),mod(null,null),mod(0,0),mod(7,4)fromdual
MOD(7,4)
-------3

MOD(1,5) MOD(NULL,NULL)
-------- -------------1

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

MOD(0,0) MOD(-7,4)
-------- --------0
-3
18 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

E. NVL
Thiswillsubstitutesthespecifiedvalueintheplaceofnullvalues.
Syntax:
nvl(null_col,replacement_value)
Ex:
SQL>select*fromstudentherefor3rdrowmarksvalueisnull
NO
-1
2
3

NAME
---a
b
c

MARKS
--------100
200

SQL>selectno,name,nvl(marks,300)fromstudent
NO NAME
-- ---1
a
2
b
3
c

NVL(MARKS,300)
-------------100
200
300

SQL>selectnvl(1,2),nvl(2,3),nvl(4,3),nvl(5,4)fromdual
NVL(1,2)
-------1

NVL(2,3)
-------2

NVL(4,3)
-------4

NVL(5,4)
-------5

SQL>selectnvl(0,0),nvl(1,1),nvl(null,null),nvl(4,4)fromdual
NVL(0,0)
-------0

NVL(1,1) NVL(null,null) NVL(4,4)


-------- -------------- ---------1
4

F. POWER
Poweristheabilitytoraiseavaluetoagivenexponent.
Syntax:
power(value,exponent)
Ex:
SQL>selectpower(2,5),power(0,0),power(1,1),power(null,null),power(2,5)fromdual
POWER(2,5) POWER(0,0) POWER(1,1) POWER(NULL,NULL) POWER(2,-5)
---------- ---------- --------- ----------------- --------------32
1
1
.03125

G. EXP
Thiswillraiseevaluetothegivepower.
Syntax:
exp(value)
Ex:
SQL>selectexp(1),exp(2),exp(0),exp(null),exp(2)fromdual
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

19/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

EXP(1)
EXP(2)
EXP(0)
EXP(NULL)
EXP(-2)
---------------- ----------------------2.71828183 7.3890561
1
.135335283

H. LN
Thisisbasedonnaturalorbaseelogarithm.
Syntax:
ln(value)herevaluemustbegreaterthanzerowhichispositiveonly.
Ex:
SQL>selectln(1),ln(2),ln(null)fromdual
LN(1)
-----0

LN(2)
LN(NULL)
-----------------.693147181

LnandExparereciprocaltoeachother.
EXP(3)=20.0855369
LN(20.0855369)=3
I. LOG
Thisisbasedon10basedlogarithm.
Syntax:
log(10,value)herevaluemustbegreaterthanzerowhichispositiveonly.
Ex:
SQL>selectlog(10,100),log(10,2),log(10,1),log(10,null)fromdual
LOG(10,100) LOG(10,2) LOG(10,1) LOG(10,NULL)
----------- ----------- --------- ----------------2
.301029996
0

LN(value)=LOG(EXP(1),value)
SQL>selectln(3),log(exp(1),3)fromdual
LN(3)
------1.09861229

LOG(EXP(1),3)
----------------1.09861229

J. CEIL
Thiswillproduceawholenumberthatisgreaterthanorequaltothespecifiedvalue.
Syntax:
ceil(value)
Ex:
SQL>selectceil(5),ceil(5.1),ceil(5),ceil(5.1),ceil(0),ceil(null)fromdual
CEIL(5) CEIL(5.1) CEIL(-5) CEIL(-5.1) CEIL(0) CEIL(NULL)
------- --------- -------- ---------- ------- ---------5
6
-5
-5
0

K. FLOOR
Thiswillproduceawholenumberthatislessthanorequaltothespecifiedvalue.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

20/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Syntax:
floor(value)
Ex:
SQL>selectfloor(5),floor(5.1),floor(5),floor(5.1),floor(0),floor(null)fromdual
FLOOR(5) FLOOR(5.1) FLOOR(-5) FLOOR(-5.1) FLOOR(0) FLOOR(NULL)
-------- ---------- -------- ----------- --------- ----------5
5
-5
-6
0

L. ROUND
Thiswillroundsnumberstoagivennumberofdigitsofprecision.
Syntax:
round(value,precision)
Ex:
SQL>selectround(123.2345),round(123.2345,2),round(123.2354,2)fromdual
ROUND(123.2345) ROUND(123.2345,0) ROUND(123.2345,2) ROUND(123.2354,2)
--------------- ----------------- ----------------- ----------------123
123
123.23
123.24

SQL>selectround(123.2345,1),round(123.2345,2),round(123.2345,3),round(123.2345,4)from
dual
ROUND(123.2345,-1) ROUND(123.2345,-2) ROUND(123.2345,-3) ROUND(123.2345,-4)
------------------ ------------------ ------------------ -----------------120
100
0
0

SQL>selectround(123,0),round(123,1),round(123,2)fromdual
ROUND(123,0) ROUND(123,1) ROUND(123,2)
----------- ------------ -----------123
123
123

SQL>selectround(123,0),round(123,1),round(123,2)fromdual
ROUND(-123,0) ROUND(-123,1) ROUND(-123,2)
------------ ------------- -------------123
-123
-123

SQL>selectround(123,1),round(123,2),round(123,3),round(123,1),round(123,2),
round(123,3)fromdual
ROUND(123,-1) ROUND(123,-2) ROUND(123,-3) ROUND(-123,-1) ROUND(-123,-2) ROUND(-123,-3)
------------- ------------- ------------- -------------- -------------- -------------120
100
0
-120
-100
0

SQL>selectround(null,null),round(0,0),round(1,1),round(1,1),round(2,2)fromdual
ROUND(NULL,NULL) ROUND(0,0) ROUND(1,1) ROUND(-1,-1) ROUND(-2,-2)
---------------- ---------- ---------- ------------ -----------0
1
0
0

M. TRUNC
Thiswilltruncatesorchopsoffdigitsofprecisionfromanumber.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

21/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Syntax:
trunc(value,precision)
Ex:
SQL>selecttrunc(123.2345),trunc(123.2345,2),trunc(123.2354,2)fromdual
TRUNC(123.2345) TRUNC(123.2345,2) TRUNC(123.2354,2)
--------------- ----------------- ----------------123
123.23
123.23

SQL>selecttrunc(123.2345,1),trunc(123.2345,2),trunc(123.2345,3),trunc(123.2345,4)from
dual
TRUNC(123.2345,-1) TRUNC(123.2345,-2) TRUNC(123.2345,-3) TRUNC(123.2345,-4)
------------------ ------------------ ------------------ -----------------120
100
0
0

SQL>selecttrunc(123,0),trunc(123,1),trunc(123,2)fromdual
TRUNC(123,0) TRUNC(123,1) TRUNC(123,2)
------------ ------------ ----------123
123
123

SQL>selecttrunc(123,0),trunc(123,1),trunc(123,2)fromdual
TRUNC(-123,0) TRUNC(-123,1) TRUNC(-123,2)
------------- ------------- -------------123
-123
-123

SQL>selecttrunc(123,1),trunc(123,2),trunc(123,3),trunc(123,1),trunc(123,2),trunc(123,3)
fromdual
TRUNC(123,-1) TRUNC(123,-2) TRUNC(123,-3) TRUNC(-123,-1) TRUNC(-123,2) TRUNC(-123,-3)
------------- ------------- ------------- -------------- ------------- -------------120
100
0
-120
-123
0

SQL>selecttrunc(null,null),trunc(0,0),trunc(1,1),trunc(1,1),trunc(2,2)fromdual
TRUNC(NULL,NULL) TRUNC(0,0) TRUNC(1,1) TRUNC(-1,-1) TRUNC(-2,-2)
---------------- ---------- ---------- ------------ ---------------0
1
0
0

N. BITAND
Thiswillperformbitwiseandoperation.
Syntax:
bitand(value1,value2)
Ex:
SQL>selectbitand(2,3),bitand(0,0),bitand(1,1),bitand(null,null),bitand(2,3)fromdual
BITAND(2,3) BITAND(0,0) BITAND(1,1) BITAND(NULL,NULL) BITAND(-2,-3)
----------- ---------- ----------- ---------------- ------------2
0
1
-4

O. GREATEST
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

22/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Thiswillgivethegreatestnumber.
Syntax:
greatest(value1,value2,value3...valuen)
Ex:
SQL>selectgreatest(1,2,3),greatest(1,2,3)fromdual
GREATEST(1,2,3) GREATEST(-1,-2,-3)
--------------- -----------------3
-1

Ifallthevaluesarezerosthenitwilldisplayzero.
Ifalltheparametersarenullsthenitwilldisplaynothing.
Ifanyoftheparametersisnullitwilldisplaynothing.
P. LEAST
Thiswillgivetheleastnumber.
Syntax:
least(value1,value2,value3...valuen)
Ex:
SQL>selectleast(1,2,3),least(1,2,3)fromdual
LEAST(1,2,3)
-----------1

LEAST(-1,-2,-3)
---------------3

Ifallthevaluesarezerosthenitwilldisplayzero.
Ifalltheparametersarenullsthenitwilldisplaynothing.
Ifanyoftheparametersisnullitwilldisplaynothing.
Q. COALESCE
Thiswillreturnfirstnonnullvalue.
Syntax:
coalesce(value1,value2,value3...valuen)
Ex:
SQL>selectcoalesce(1,2,3),coalesce(null,2,null,5)fromdual
COALESCE(1,2,3)
--------------1

COALESCE(NULL,2,NULL,5)
----------------------2

STRINGFUNCTIONS
Initcap
Upper
Lower
Length
Rpad
Lpad
Ltrim
Rtrim
Trim
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

23 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Translate
Replace
Soundex
Concat('||'Concatenationoperator)
Ascii
Chr
Substr
Instr
Decode
Greatest
Least
Coalesce
A. INITCAP
Thiswillcapitalizetheinitialletterofthestring.
Syntax:
initcap(string)
Ex:
SQL>selectinitcap('computer')fromdual
INITCAP
-------Computer

B. UPPER
Thiswillconvertthestringintouppercase.
Syntax:
upper(string)
Ex:
SQL>selectupper('computer')fromdual
UPPER
--------COMPUTER

C. LOWER
Thiswillconvertthestringintolowercase.
Syntax:
lower(string)
Ex:
SQL>selectlower('COMPUTER')fromdual
LOWER
--------computer

D. LENGTH
Thiswillgivelengthofthestring.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

24/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Syntax:
length(string)
Ex:
SQL>selectlength('computer')fromdual
LENGTH
------8

E. RPAD
Thiswillallowsyoutopadtherightsideofacolumnwithanysetofcharacters.
Syntax:
rpad(string,length[,padding_char])
Ex:
SQL>selectrpad('computer',15,'*'),rpad('computer',15,'*#')fromdual
RPAD('COMPUTER'
--------------computer*******

RPAD('COMPUTER'
---------------computer*#*#*#*

Defaultpaddingcharacterwasblankspace.
F. LPAD
Thiswillallowsyoutopadtheleftsideofacolumnwithanysetofcharacters.
Syntax:
lpad(string,length[,padding_char])
Ex:
SQL>selectlpad('computer',15,'*'),lpad('computer',15,'*#')fromdual
LPAD('COMPUTER'
--------------*******computer

LPAD('COMPUTER'
-----------------*#*#*#*computer

Defaultpaddingcharacterwasblankspace.
G. LTRIM
Thiswilltrimoffunwantedcharactersfromtheleftendofstring.
Syntax:
ltrim(string[,unwanted_chars])
Ex:
SQL>selectltrim('computer','co'),ltrim('computer','com')fromdual
LTRIM(
LTRIM
-------- --------mputer
puter

SQL>selectltrim('computer','puter'),ltrim('computer','omputer')fromdual
LTRIM('C
---------computer

LTRIM('C
---------computer

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

25 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Ifyouhaven'tspecifyanyunwantedcharactersitwilldisplayentirestring.
H. RTRIM
Thiswilltrimoffunwantedcharactersfromtherightendofstring.
Syntax:
rtrim(string[,unwanted_chars])
Ex:
SQL>selectrtrim('computer','er'),rtrim('computer','ter')fromdual
RTRIM(
RTRIM
-------- --------comput
compu

SQL>selectrtrim('computer','comput'),rtrim('computer','compute')fromdual
RTRIM('C
---------computer

RTRIM('C
---------computer

Ifyouhaven'tspecifyanyunwantedcharactersitwilldisplayentirestring.
I. TRIM
Thiswilltrimoffunwantedcharactersfromthebothsidesofstring.
Syntax:
trim(unwanted_charsfromstring)
Ex:
SQL>selecttrim('i'from'indiani')fromdual
TRIM(
----ndian

SQL>selecttrim(leading'i'from'indiani')fromdualthiswillworkasLTRIM
TRIM(L
-----ndiani

SQL>selecttrim(trailing'i'from'indiani')fromdualthiswillworkasRTRIM
TRIM(T
-----Indian

J. TRANSLATE
Thiswillreplacethesetofcharacters,characterbycharacter.
Syntax:
translate(string,old_chars,new_chars)
Ex:
SQL>selecttranslate('india','in','xy')fromdual
TRANS
-------xydxa
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

26/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

K. REPLACE
Thiswillreplacethesetofcharacters,stringbystring.
Syntax:
replace(string,old_chars[,new_chars])
Ex:
SQL>selectreplace('india','in','xy'),replace('india','in')fromdual
REPLACE
REPLACE
----------- ----------Xydia
dia

L. SOUNDEX
Thiswillbeusedtofindwordsthatsoundlikeotherwords,exclusivelyusedinwhereclause.
Syntax:
soundex(string)
Ex:
SQL>select*fromempwheresoundex(ename)=soundex('SMIT')
EMPNO ENAME
JOB
----- ------ ----7369 SMITH CLERK

MGR
HIREDATE
---- -----------7902 17-DEC-80

SAL
DEPTNO
----- -------500
20

M. CONCAT
Thiswillbeusedtocombinetwostringsonly.
Syntax:
concat(string1,string2)
Ex:
SQL>selectconcat('computer','operator')fromdual
CONCAT('COMPUTER'
-----------------computer operator

Ifyouwanttocombinemorethantwostringsyouhavetouseconcatenationoperator(||).
SQL>select'how'||'are'||'you'fromdual
'HOW'||'ARE
-----------how are you

N. ASCII
Thiswillreturnthedecimalrepresentationinthedatabasecharactersetofthefirstcharacterofthestring.
Syntax:
ascii(string)
Ex:
SQL>selectascii('a'),ascii('apple')fromdual
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

27/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

ASCII('A') ASCII('APPLE')
------------ -----------97
97

O. CHR
Thiswillreturnthecharacterhavingthebinaryequivalenttothestringineitherthedatabasecharacterset
orthenationalcharacterset.
Syntax:
chr(number)
Ex:
SQL>selectchr(97)fromdual
CHR
----a

P. SUBSTR
Thiswillbeusedtoextractsubstrings.
Syntax:
substr(string,start_chr_count[,no_of_chars])
Ex:
SQL>selectsubstr('computer',2),substr('computer',2,5),substr('computer',3,7)fromdual
SUBSTR(
-------omputer

SUBST
------omput

SUBSTR
-------mputer

Ifno_of_charsparameterisnegativethenitwilldisplaynothing.
Ifbothparametersexceptstringarenullorzerosthenitwilldisplaynothing.
Ifno_of_charsparameterisgreaterthanthelengthofthestringthenitignoresandcalculatesbasedon
theorginalstringlength.
Ifstart_chr_countisnegativethenitwillextractthesubstringfromrightend.
1

-8

-7

-6

-5

-4

-3

-2

-1

Q. INSTR
Thiswillallowsyouforsearchingthroughastringforsetofcharacters.
Syntax:
instr(string,search_str[,start_chr_count[,occurrence]])
Ex:
SQL>selectinstr('information','o',4,1),instr('information','o',4,2)fromdual
INSTR('INFORMATION','O',4,1)
--------------------------4
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

INSTR('INFORMATION','O',4,2)
---------------------------10
28 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Ifyouarenotspecifyingstart_chr_countandoccurrencethenitwillstartsearchfromthebeginning
andfindsfirstoccurrenceonly.
Ifbothparametersstart_chr_countandoccurrencearenull,itwilldisplaynothing.
R. DECODE
Decodewillactasvaluebyvaluesubstitution.Foreveryvalueoffield,itwillchecksforamatchina
seriesofif/thentests.
Syntax:
decode(value,if1,then1,if2,then2,.......else)
Ex:
SQL>selectsal,decode(sal,500,'Low',5000,'High','Medium')fromemp
SAL
----500
2500
2000
3500
3000
5000
4000
5000
1800
1200
2000
2700
2200
3200

DECODE
--------Low
Medium
Medium
Medium
Medium
High
Medium
High
Medium
Medium
Medium
Medium
Medium
Medium

SQL>selectdecode(1,1,3),decode(1,2,3,4,4,6)fromdual
DECODE(1,1,3)
DECODE(1,2,3,4,4,6)
----------------- -----------------------3
6

Ifthenumberofparametersareoddanddifferentthendecodewilldisplaynothing.
Ifthenumberofparametersareevenanddifferentthendecodewilldisplaylastvalue.
Ifalltheparametersarenullthendecodewilldisplaynothing.
Ifalltheparametersarezerosthendecodewilldisplayzero.
S. GREATEST
Thiswillgivethegreateststring.
Syntax:
greatest(strng1,string2,string3...stringn)
Ex:
SQL>selectgreatest('a','b','c'),greatest('satish','srinu','saketh')fromdual
GREAT
GREAT
------- ------c
srinu

Ifalltheparametersarenullsthenitwilldisplaynothing.
Ifanyoftheparametersisnullitwilldisplaynothing.
T. LEAST
Thiswillgivetheleaststring.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

29/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Syntax:
greatest(strng1,string2,string3...stringn)
Ex:
SQL>selectleast('a','b','c'),least('satish','srinu','saketh')fromdual
LEAST
LEAST
------- ------a
saketh

Ifalltheparametersarenullsthenitwilldisplaynothing.
Ifanyoftheparametersisnullitwilldisplaynothing.
U. COALESCE
Thiswillgivesthefirstnonnullstring.
Syntax:
coalesce(strng1,string2,string3...stringn)
Ex:
SQL>selectcoalesce('a','b','c'),coalesce(null,'a',null,'b')fromdual
COALESCE
----------a

COALESCE
----------a

DATEFUNCTIONS
Sysdate
Current_date
Current_timestamp
Systimestamp
Localtimestamp
Dbtimezone
Sessiontimezone
To_char
To_date
Add_months
Months_between
Next_day
Last_day
Extract
Greatest
Least
Round
Trunc
New_time
Coalesce
OracledefaultdateformatisDDMONYY.
Wecanchangethedefaultformattoourdesiredformatbyusingthefollowingcommand.
SQL>altersessionsetnls_date_format='DDMONTHYYYY'
Butthiswillexpireoncethesessionwasclosed.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

3 0/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

A. SYSDATE
Thiswillgivethecurrentdateandtime.
Ex:
SQL>selectsysdatefromdual
SYSDATE
----------24-DEC-06

B. CURRENT_DATE
Thiswillreturnsthecurrentdateinthesession'stimezone.
Ex:
SQL>selectcurrent_datefromdual
CURRENT_DATE
-----------------24-DEC-06

C. CURRENT_TIMESTAMP
Thiswillreturnsthecurrenttimestampwiththeactivetimezoneinformation.
Ex:
SQL>selectcurrent_timestampfromdual
CURRENT_TIMESTAMP
----------------------------------------24-DEC-06 03.42.41.383369 AM +05:30

D. SYSTIMESTAMP
Thiswillreturnsthesystemdate,includingfractionalsecondsandtimezoneofthedatabase.
Ex:
SQL>selectsystimestampfromdual
SYSTIMESTAMP
-----------------------------------24-DEC-06 03.49.31.830099 AM +05:30

E. LOCALTIMESTAMP
Thiswillreturnslocaltimestampintheactivetimezoneinformation,withnotimezoneinformation
shown.
Ex:
SQL>selectlocaltimestampfromdual
LOCALTIMESTAMP
----------------------------24-DEC-06 03.44.18.502874 AM

F. DBTIMEZONE
ThiswillreturnsthecurrentdatabasetimezoneinUTCformat.(CoordinatedUniversalTime)
Ex:
SQL>selectdbtimezonefromdual
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

3 1/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

DBTIMEZONE
---------------07:00

G. SESSIONTIMEZONE
Thiswillreturnsthevalueofthecurrentsession'stimezone.
Ex:
SQL>selectsessiontimezonefromdual
SESSIONTIMEZONE
---------------+05:30

H. TO_CHAR
Thiswillbeusedtoextractvariousdateformats.Theavailabledateformatsasfollows.
Syntax:
to_char(date,format)
DATEFORMATS
D
DD
DDD
MM
MON
MONTH -RM
DY
DAY
Y
YY
YYY
YYYY
SYYYY -I
IY
IYY
IYYY
Y, YYY
YEAR
CC
Q
W
WW
IW
HH
MI
SS
FF
AM or PM
A.M or P.M
AD or BC
A.D or B.C
FM
TH
SP

-No of days in week


-No of days in month
-No of days in year
-No of month
-Three letter abbreviation of month
Fully spelled out month
-Roman numeral month
-Three letter abbreviated day
-Fully spelled out day
-Last one digit of the year
-Last two digits of the year
-Last three digits of the year
-Full four digit year
Signed year
-One digit year from ISO standard
-Two digit year from ISO standard
-Three digit year from ISO standard
-Four digit year from ISO standard
-Year with comma
-Fully spelled out year
-Century
-No of quarters
-No of weeks in month
-No of weeks in year
-No of weeks in year from ISO standard
-Hours
-Minutes
-Seconds
-Fractional seconds
-Displays AM or PM depending upon time of day
-Displays A.M or P.M depending upon time of day
-Displays AD or BC depending upon the date
-Displays AD or BC depending upon the date
-Prefix to month or day, suppresses padding of month or day
-Suffix to a number
-suffix to a number to be spelled out

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

3 2/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SPTH
THSP

---

Suffix combination of TH and SP to be both spelled out


same as SPTH

Ex:
SQL>selectto_char(sysdate,'ddmonthyyyyhh:mi:ssamdy')fromdual
TO_CHAR(SYSDATE,'DD MONTH YYYYHH:MI
-----------------------------------24 december 2006 02:03:23 pm sun

SQL>selectto_char(sysdate,'ddmonthyear')fromdual
TO_CHAR(SYSDATE,'DDMONTHYEAR')
------------------------------24 december two thousand six

SQL>selectto_char(sysdate,'ddfmmonthyear')fromdual
TO_CHAR(SYSDATE,'DD FMMONTH YEAR')
---------------------------------24 december two thousand six

SQL>selectto_char(sysdate,'ddthDDTH')fromdual
TO_CHAR(S
-----------24th 24TH

SQL>selectto_char(sysdate,'ddspthDDSPTH')fromdual
TO_CHAR(SYSDATE,'DDSPTHDDSPTH
----------------------------twenty-fourth TWENTY-FOURTH

SQL>selectto_char(sysdate,'ddspDdspDDSP')fromdual
TO_CHAR(SYSDATE,'DDSPDDSPDDSP')
-----------------------------------twenty-four Twenty-Four TWENTY-FOUR

I. TO_DATE
Thiswillbeusedtoconvertthestringintodataformat.
Syntax:
to_date(date)
Ex:
SQL>selectto_char(to_date('24/dec/2006','dd/mon/yyyy'),'dd*month*day')fromdual
TO_CHAR(TO_DATE('24/DEC/20
-------------------------24 * december * Sunday

Ifyouarenotusingto_charoraclewilldisplayoutputindefaultdateformat.
J. ADD_MONTHS
Thiswilladdthespecifiedmonthstothegivendate.
Syntax:
add_months(date,no_of_months)
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

3 3 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Ex:
SQL>selectadd_months(to_date('11jan1990','ddmonyyyy'),5)fromdual
ADD_MONTHS
----------11-JUN-90

SQL>selectadd_months(to_date('11jan1990','ddmonyyyy'),5)fromdual
ADD_MONTH
---------11-AUG-89

Ifno_of_monthsiszerothenitwilldisplaythesamedate.
Ifno_of_monthsisnullthenitwilldisplaynothing.
K. MONTHS_BETWEEN
Thiswillgivedifferenceofmonthsbetweentwodates.
Syntax:
months_between(date1,date2)
Ex:
SQL>selectmonths_between(to_date('11aug1990','ddmonyyyy'),to_date('11jan1990','dd
monyyyy'))fromdual
MONTHS_BETWEEN(TO_DATE('11-AUG-1990','DD-MON-YYYY'),TO_DATE('11-JAN-1990','DD-MON-YYYY'))
--------------------------------------------------------------------------------------7

SQL>selectmonths_between(to_date('11jan1990','ddmonyyyy'),to_date('11aug1990','dd
monyyyy'))fromdual
MONTHS_BETWEEN(TO_DATE('11-JAN-1990','DD-MON-YYYY'),TO_DATE('11-AUG-1990','DD-MON-YYYY'))
----------------------------------------------------------------------------------------7

L. NEXT_DAY
Thiswillproducenextdayofthegivendayfromthespecifieddate.
Syntax:
next_day(date,day)
Ex:
SQL>selectnext_day(to_date('24dec2006','ddmonyyyy'),'sun')fromdual
NEXT_DAY(
---------31-DEC-06

Ifthedayparameterisnullthenitwilldisplaynothing.
M. LAST_DAY
Thiswillproducelastdayofthegivendate.
Syntax:
last_day(date)
Ex:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

3 4/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>selectlast_day(to_date('24dec2006','ddmonyyyy'),'sun')fromdual
LAST_DAY(
---------31-DEC-06

N. EXTRACT
Thisisusedtoextractaportionofthedatevalue.
Syntax:
extract((year|month|day|hour|minute|second),date)
Ex:
SQL>selectextract(yearfromsysdate)fromdual
EXTRACT(YEARFROMSYSDATE)
-----------------------2006

Youcanextractonlyonevalueatatime.
O. GREATEST
Thiswillgivethegreatestdate.
Syntax:
greatest(date1,date2,date3...daten)
Ex:
SQL>selectgreatest(to_date('11jan90','ddmonyy'),to_date('11mar90','ddmon
yy'),to_date('11apr90','ddmonyy'))fromdual
GREATEST(
----------11-APR-90

P. LEAST
Thiswillgivetheleastdate.
Syntax:
least(date1,date2,date3...daten)
Ex:
SQL>selectleast(to_date('11jan90','ddmonyy'),to_date('11mar90','ddmonyy'),to_date('11
apr90','ddmonyy'))fromdual
LEAST(
----------11-JAN-90

Q. ROUND
Roundwillroundsthedatetowhichitwasequaltoorgreaterthanthegivendate.
Syntax:
round(date,(day|month|year))
Ifthesecondparameterwasyearthenroundwillchecksthemonthofthegivendateinthefollowing
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

3 5 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

ranges.
JAN
-JUL -- DEC

JUN

IfthemonthfallsbetweenJANandJUNthenitreturnsthefirstdayofthecurrentyear.Ifthemonthfalls
betweenJULandDECthenitreturnsthefirstdayofthenextyear.
Ifthesecondparameterwasmonththenroundwillchecksthedayofthegivendateinthefollowing
ranges.
1
16

---

15
31

Ifthedayfallsbetween1and15thenitreturnsthefirstdayofthecurrentmonth.Ifthedayfallsbetween
16and31thenitreturnsthefirstdayofthenextmonth.
Ifthesecondparameterwasdaythenroundwillcheckstheweekdayofthegivendateinthefollowing
ranges.
SUN
-THU -- SUN

WED

IftheweekdayfallsbetweenSUNandWEDthenitreturnstheprevioussunday.
IftheweekdayfallsbetweenTHUandSUNthenitreturnsthenextsunday.
Ifthesecondparameterwasnullthenitreturnsnothing.
Iftheyouarenotspecifyingthesecondparameterthenroundwillresetsthetimetothebeginingof
thecurrentdayincaseofuserspecifieddate.
Iftheyouarenotspecifyingthesecondparameterthenroundwillresetsthetimetothebeginingof
thenextdayincaseofsysdate.
Ex:
SQL>selectround(to_date('24dec04','ddmonyy'),'year'),round(to_date('11mar06','ddmon
yy'),'year')fromdual
ROUND(TO_
-----------01-JAN-05

ROUND(TO_
--------------01-JAN-06

SQL>selectround(to_date('11jan04','ddmonyy'),'month'),round(to_date('18jan04','ddmon
yy'),'month')fromdual
ROUND(TO_
ROUND(TO_
------------- --------------01-JAN-04
01-FEB-04

SQL>selectround(to_date('26dec06','ddmonyy'),'day'),round(to_date('29dec06','ddmon
yy'),'day')fromdual
ROUND(TO_
ROUND(TO_
-------------- -------------24-DEC-06
31-DEC-06

SQL>selectto_char(round(to_date('24dec06','ddmonyy')),'ddmonyyyyhh:mi:ssam')from
dual
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

3 6/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

TO_CHAR(ROUND(TO_DATE('
-----------------------24 dec 2006 12:00:00 am

R. TRUNC
Truncwillchopsoffthedatetowhichitwasequaltoorlessthanthegivendate.
Syntax:
trunc(date,(day|month|year))
Ifthesecondparameterwasyearthenitalwaysreturnsthefirstdayofthecurrentyear.
Ifthesecondparameterwasmonththenitalwaysreturnsthefirstdayofthecurrentmonth.
Ifthesecondparameterwasdaythenitalwaysreturnstheprevioussunday.
Ifthesecondparameterwasnullthenitreturnsnothing.
Iftheyouarenotspecifyingthesecondparameterthentrunkwillresetsthetimetothebeginingofthe
currentday.
Ex:
SQL>selecttrunc(to_date('24dec04','ddmonyy'),'year'),trunc(to_date('11mar06','ddmon
yy'),'year')fromdual
TRUNC(TO_
TRUNC(TO_
------------- -----------01-JAN-04
01-JAN-06

SQL>selecttrunc(to_date('11jan04','ddmonyy'),'month'),trunc(to_date('18jan04','ddmon
yy'),'month')fromdual
TRUNC(TO_
TRUNC(TO_
------------- -----------01-JAN-04
01-JAN-04

SQL>selecttrunc(to_date('26dec06','ddmonyy'),'day'),trunc(to_date('29dec06','ddmon
yy'),'day')fromdual
TRUNC(TO_
TRUNC(TO_
------------- -------24-DEC-06
24-DEC-06

SQL>selectto_char(trunc(to_date('24dec06','ddmonyy')),'ddmonyyyyhh:mi:ssam')from
dual
TO_CHAR(TRUNC(TO_DATE('
-----------------------24 dec 2006 12:00:00 am

S. NEW_TIME
Thiswillgivethedesiredtimezone'sdateandtime.
Syntax:
new_time(date,current_timezone,desired_timezone)
Availabletimezonesareasfollows.TIMEZONES
AST/ADT -BST/BDT -CST/CDT -EST/EDT -h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

Atlantic standard/day light time


Bering standard/day light time
Central standard/day light time
Eastern standard/day light time
3 7/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

GMT
-HST/HDT -MST/MDT -NST
-PST/PDT -YST/YDT --

Greenwich mean time


Alaska-Hawaii standard/day light time
Mountain standard/day light time
Newfoundland standard time
Pacific standard/day light time
Yukon standard/day light time

Ex:
SQL>selectto_char(new_time(sysdate,'gmt','yst'),'ddmonyyyyhh:mi:ssam')fromdual
TO_CHAR(NEW_TIME(SYSDAT
-----------------------24 dec 2006 02:51:20 pm

SQL>selectto_char(new_time(sysdate,'gmt','est'),'ddmonyyyyhh:mi:ssam')fromdual
TO_CHAR(NEW_TIME(SYSDAT
----------------------24 dec 2006 06:51:26 pm

T. COALESCE
Thiswillgivethefirstnonnulldate.
Syntax:
coalesce(date1,date2,date3...daten)
Ex:
SQL>selectcoalesce('12jan90','13jan99'),coalesce(null,'12jan90','23mar98',null)fromdual
COALESCE(
COALESCE(
---------- -----------12-jan-90
12-jan-90

MISCELLANEOUSFUNCTIONS
Uid
User
Vsize
Rank
Dense_rank
A. UID
Thiswillreturnstheintegervaluecorrespondingtotheusercurrentlyloggedin.
Ex:
SQL>selectuidfromdual
UID
----319

B. USER
Thiswillreturnsthelogin'susername.
Ex:
SQL>selectuserfromdual
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

3 8 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

USER
-----SAKETH

C. VSIZE
Thiswillreturnsthenumberofbytesintheexpression.
Ex:
SQL>selectvsize(123),vsize('computer'),vsize('12jan90')fromdual
VSIZE(123)
---------3

VSIZE('COMPUTER') VSIZE('12-JAN-90')
----------------- -----------------8
9

D. RANK
Thiswillgivethenonsequentialranking.
Ex:
SQL>selectrownum,salfrom(selectsalfromemporderbysaldesc)
ROWNUM
SAL
---------- ---------1
5000
2
3000
3
3000
4
2975
5
2850
6
2450
7
1600
8
1500
9
1300
10
1250
11
1250
12
1100
13
1000
14
950
15
800

SQL>selectrank(2975)withingroup(orderbysaldesc)fromemp
RANK(2975)WITHINGROUP(ORDERBYSALDESC)
-----------------------------------4

E. DENSE_RANK
Thiswillgivethesequentialranking.
Ex:
SQL>selectdense_rank(2975)withingroup(orderbysaldesc)fromemp
DENSE_RANK(2975)WITHINGROUP(ORDERBYSALDESC)
-----------------------------------------3

CONVERSIONFUNCTIONS
Bin_to_num
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

3 9/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Chartorowid
Rowidtochar
To_number
To_char
To_date
A. BIN_TO_NUM
Thiswillconvertthebinaryvaluetoitsnumericalequivalent.
Syntax:
bin_to_num(binary_bits)
Ex:
SQL>selectbin_to_num(1,1,0)fromdual
BIN_TO_NUM(1,1,0)
----------------6

Ifallthebitsarezerothenitproduceszero.
Ifallthebitsarenullthenitproducesanerror.
B. CHARTOROWID
Thiswillconvertacharacterstringtoactlikeaninternaloraclerowidentifierorrowid.
C. ROWIDTOCHAR
Thiswillconvertaninternaloraclerowidentifierorrowidtocharacterstring.
D. TO_NUMBER
Thiswillconvertacharorvarchartonumber.
E. TO_CHAR
Thiswillconvertanumberordatetocharacterstring.
F. TO_DATE
Thiswillconvertanumber,charorvarchartoadate.
GROUPFUNCTIONS
Sum
Avg
Max
Min
Count
Groupfunctionswillbeappliedonalltherowsbutproducessingleoutput.
A. SUM
Thiswillgivethesumofthevaluesofthespecifiedcolumn.
Syntax:
sum(column)
Ex:
SQL>selectsum(sal)fromemp
SUM(SAL)
---------38600

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

40/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

B. AVG
Thiswillgivetheaverageofthevaluesofthespecifiedcolumn.
Syntax:
avg(column)
Ex:
SQL>selectavg(sal)fromemp
AVG(SAL)
--------------2757.14286

C. MAX
Thiswillgivethemaximumofthevaluesofthespecifiedcolumn.
Syntax:
max(column)
Ex:
SQL>selectmax(sal)fromemp
MAX(SAL)
---------5000

D. MIN
Thiswillgivetheminimumofthevaluesofthespecifiedcolumn.
Syntax:
min(column)
Ex:
SQL>selectmin(sal)fromemp
MIN(SAL)
---------500

E. COUNT
Thiswillgivethecountofthevaluesofthespecifiedcolumn.
Syntax:
count(column)
Ex:
SQL>selectcount(sal),count(*)fromemp
COUNT(SAL) COUNT(*)
------------------------14
14

CONSTRAINTS
Constraintsarecategorizedasfollows.
Domainintegrityconstraints
Notnull
Check
Entityintegrityconstraints
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

41/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Unique
Primarykey
Referentialintegrityconstraints
Foreignkey
Constraintsarealwaysattachedtoacolumnnotatable.
Wecanaddconstraintsinthreeways.
Columnlevelalongwiththecolumndefinition
Tablelevelafterthetabledefinition
Alterlevelusingaltercommand
Whileaddingconstraintsyouneednotspecifythenamebutthetypeonly,oraclewillinternallynamethe
constraint.
Ifyouwanttogiveanametotheconstraint,youhavetousetheconstraintclause.
NOTNULL
Thisisusedtoavoidnullvalues.
Wecanaddthisconstraintincolumnlevelonly.
Ex:
SQL>createtablestudent(nonumber(2)notnull,namevarchar(10),marksnumber(3))
SQL>createtablestudent(nonumber(2)constraintnnnotnull,namevarchar(10),marksnumber(3))
CHECK
Thisisusedtoinsertthevaluesbasedonspecifiedcondition.
Wecanaddthisconstraintinallthreelevels.
Ex:
COLUMNLEVEL
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3)check(marks>300))
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3)constraintch
check(marks>300))
TABLELEVEL
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3),check(marks>300))
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3),constraintch
check(marks>300))
ALTERLEVEL
SQL>altertablestudentaddcheck(marks>300)
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

42/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>altertablestudentaddconstraintchcheck(marks>300)
UNIQUE
Thisisusedtoavoidduplicatesbutitallownulls.
Wecanaddthisconstraintinallthreelevels.
Ex:
COLUMNLEVEL
SQL>createtablestudent(nonumber(2)unique,namevarchar(10),marksnumber(3))
SQL>createtablestudent(nonumber(2)constraintununique,namevarchar(10),marksnumber(3))
TABLELEVEL
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3),unique(no))
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3),constraintun
unique(no))
ALTERLEVEL
SQL>altertablestudentaddunique(no)
SQL>altertablestudentaddconstraintununique(no)
PRIMARYKEY
Thisisusedtoavoidduplicatesandnulls.Thiswillworkascombinationofuniqueandnotnull.Primarykey
alwaysattachedtotheparenttable.Wecanaddthisconstraintinallthreelevels.
Ex:
COLUMNLEVEL
SQL>createtablestudent(nonumber(2)primarykey,namevarchar(10),marksnumber(3))
SQL>createtablestudent(nonumber(2)constraintpkprimarykey,namevarchar(10),marks
number(3))
TABLELEVEL
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3),primarykey(no))
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3),constraintpkprimary
key(no))
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

43 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

ALTERLEVEL
SQL>altertablestudentaddprimarykey(no)
SQL>altertablestudentaddconstraintpkprimarykey(no)
FOREIGNKEY
Thisisusedtoreferencetheparenttableprimarykeycolumnwhichallowsduplicates.Foreignkeyalways
attachedtothechildtable.Wecanaddthisconstraintintableandalterlevelsonly.
Ex:
TABLELEVEL
SQL>createtableemp(empnonumber(2),enamevarchar(10),deptnonumber(2),primary
key(empno),foreignkey(deptno)referencesdept(deptno))
SQL>createtableemp(empnonumber(2),enamevarchar(10),deptnonumber(2),constraintpkprimary
key(empno),constraintfkforeignkey(deptno)referencesdept(deptno))
ALTERLEVEL
SQL>altertableempaddforeignkey(deptno)referencesdept(deptno)
SQL>altertableempaddconstraintfkforeignkey(deptno)referencesdept(deptno)
Oncetheprimarykeyandforeignkeyrelationshiphasbeencreatedthenyoucannotremoveanyparent
recordifthedependentchildsexists.
USINGONDELTECASCADE
Byusingthisclauseyoucanremovetheparentrecordevenitchildsexists.Becausewheneveryouremove
parentrecordoracleautomaticallyremovesallitsdependentrecordsfromchildtable,ifthisclauseispresent
whilecreatingforeignkeyconstraint.
Ex:
TABLELEVEL
SQL>createtableemp(empnonumber(2),enamevarchar(10),deptnonumber(2),primarykey(empno),
foreignkey(deptno)referencesdept(deptno)ondeletecascade)
SQL>createtableemp(empnonumber(2),enamevarchar(10),deptnonumber(2),constraintpk
primarykey(empno),constraintfkforeignkey(deptno)referencesdept(deptno)ondeletecascade)
ALTERLEVEL

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

44/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>altertableempaddforeignkey(deptno)referencesdept(deptno)ondeletecascade
SQL>altertableempaddconstraintfkforeignkey(deptno)referencesdept(deptno)ondeletecascade
COMPOSITEKEYS
Acompositekeycanbedefinedonacombinationofcolumns.Wecandefinecompositekeysonentity
integrityandreferentialintegrityconstraints.Compositekeycanbedefinedintableandalterlevelsonly.
Ex:
UNIQUE(TABLELEVEL)
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3),unique(no,name))
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3),constraintun
unique(no,name))
UNIQUE(ALTERLEVEL)
SQL>altertablestudentaddunique(no,name)
SQL>altertablestudentaddconstraintununique(no,name)
PRIMARYKEY(TABLELEVEL)
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3),primary
key(no,name))
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3),constraintpkprimary
key(no,name))
PRIMARYKEY(ALTERLEVEL)
SQL>altertablestudentaddprimarykey(no,anme)
SQL>altertablestudentaddconstraintpkprimarykey(no,name)
FOREIGNKEY(TABLELEVEL)
SQL>createtableemp(empnonumber(2),enamevarchar(10),deptnonumber(2),dnamevarchar(10),
primarykey(empno),foreignkey(deptno,dname)referencesdept(deptno,dname))
SQL>createtableemp(empnonumber(2),enamevarchar(10),deptnonumber(2),dnamevarchar(10),
constraintpkprimarykey(empno),constraintfkforeignkey(deptno,dname)references
dept(deptno,dname))
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

45 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

FOREIGNKEY(ALTERLEVEL)
SQL>altertableempaddforeignkey(deptno,dname)referencesdept(deptno,dname)

SQL>altertableempaddconstraintfkforeignkey(deptno,dname)referencesdept(deptno,dname)
DEFERRABLECONSTRAINTS
Eachconstrainthastwoadditionalattributestosupportdeferredcheckingofconstraints.
Deferredinitiallyimmediate
Deferredinitiallydeferred
Deferredinitiallyimmediatechecksforconstraintviolationatthetimeofinsert.
Deferredinitiallydeferredchecksforconstraintviolationatthetimeofcommit.
Ex:
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3),constraintun
unique(no)deferredinitiallyimmediate)
SQL>createtablestudent(nonumber(2),namevarchar(10),marksnumber(3),constraintun
unique(no)deferredinitiallydeferred)
SQL>altertablestudentaddconstraintununique(no)deferrableinitiallydeferred
SQL>setconstraintsallimmediate
Thiswillenablealltheconstraintsviolationsatthetimeofinserting.
SQL>setconstraintsalldeferred
Thiswillenablealltheconstraintsviolationsatthetimeofcommit.
OPERATIONSWITHCONSTRAINTS
Possibleoperationswithconstraintsasfollows.
Enable
Disable
Enforce
Drop
ENABLE
Thiswillenabletheconstraint.Beforeenable,theconstraintwillchecktheexistingdata.
Ex:
SQL>altertablestudentenableconstraintun
DISABLE
Thiswilldisabletheconstraint.
Ex:

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

46/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>altertablestudentenableconstraintun
ENFORCE
Thiswillenforcetheconstraintratherthanenableforfutureinsertsorupdates.
Thiswillnotcheckforexistingdatawhileenforcingdata.
Ex:
SQL>altertablestudentenforceconstraintun
DROP
Thiswillremovetheconstraint.
Ex:
SQL>altertablestudentdropconstraintun
Oncethetableisdropped,constraintsautomaticallywilldrop.
CASEANDDEFAULT
CASE
Caseissimilartodecodebuteasiertounderstandwhilegoingthroughcoding
Ex:
SQL>Selectsal,CasesalWhen500then'low'When5000then'high'Else'medium'EndcaseFrom
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

DEFAULT
Defaultcanbeconsideredasasubstitutebehaviorofnotnullconstraintwhenappliedtonewrowsbeing
enteredintothetable.
Whenyoudefineacolumnwiththedefaultkeywordfollowedbyavalue,youareactuallytellingthedatabase
that,oninsertifarowwasnotassignedavalueforthiscolumn,usethedefaultvaluethatyouhavespecified.
Defaultisappliedonlyduringinsertionofnewrows.
Ex:
SQL>createtablestudent(nonumber(2)default11,namevarchar(2))
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

47/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>insertintostudentvalues(1,'a')
SQL>insertintostudent(name)values('b')
SQL>select*fromstudent
NO NAME
------ --------1
a
11
b

SQL>insertintostudentvalues(null,'c')
SQL>select*fromstudent
NO NAME
------ --------1
a
11
b

CDefaultcannotoverridenulls.
ABSTRACTDATATYPES
Sometimesyoumaywanttypewhichholdsalltypesofdataincludingnumbers,charsandspecialcharacters
somethinglikethis.Youcannotachievethisusingpredefinedtypes.
Youcandefinecustomtypeswhichholdsyourdesireddata.
Ex:
Supposeinatablewehaveaddresscolumnwhichholdshnoandcityinformation.
Wewilldefineacustomtypewhichholdsbothnumericaswellaschardata.
CREATINGADT
SQL>createtypeaddrasobject(hnonumber(3),cityvarchar(10))/
CREATINGTABLEBASEDONADT
SQL>createtablestudent(nonumber(2),namevarchar(2),addressaddr)
INSERTINGDATAINTOADTTABLES
SQL>insertintostudentvalues(1,'a',addr(111,'hyd'))
SQL>insertintostudentvalues(2,'b',addr(222,'bang'))
SQL>insertintostudentvalues(3,'c',addr(333,'delhi'))
SELECTINGDATAFROMADTTABLES
SQL>select*fromstudent
NO
--1
2
3

NAME ADDRESS(HNO, CITY)


---- -------------------a
ADDR(111, 'hyd')
b
ADDR(222, 'bang')
c
ADDR(333, 'delhi')

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

48 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>selectno,name,s.address.hno,s.address.cityfromstudents
NO
NAME
-- ---1 a
2 b
3 c

ADDRESS.HNO
ADDRESS.CITY
--------- -----------111
hyd
222
bang
333
delhi

UPDATEWITHADTTABLES
SQL>updatestudentssets.address.city='bombay'wheres.address.hno=333
SQL>selectno,name,s.address.hno,s.address.cityfromstudents
NO NAME
ADDRESS.HNO
ADDRESS.CITY
--- ------------ ---------------1
a
111
hyd
2
b
222
bang
3
c
333
bombay

DELETEWITHADTTABLES
SQL>deletestudentswheres.address.hno=111
SQL>selectno,name,s.address.hno,s.address.cityfromstudents
NO
-2
3

NAME ADDRESS.HNO ADDRESS.CITY


---- ------------ ---------------b
222
bang
c
333
bombay

DROPPINGADT
SQL>droptypeaddr
OBJECTVIEWSANDMETHODS
OBJECTVIEWS
Ifyouwanttoimplementobjectswiththeexistingtable,objectviewscomeintopicture.
Youdefinetheobjectandcreateaviewwhichrelatesthisobjecttotheexistingtablenothingbutobjectview.
Objectviewsareusedtorelatetheuserdefinedobjectstotheexistingtable.
Ex:
1. Assumethatthetablestudenthasalreadybeencreatedwiththefollowingcolumns
SQL>createtablestudent(nonumber(2),namevarchar(10),hnonumber(3),cityvarchar(10))
2. Createthefollowingtypes
SQL>createtypeaddrasobject(hnonumber(2),cityvarchar(10))/
SQL>createtypestudasobject(namevarchar(10),addressaddr)/
3. Relatetheobjectstothestudenttablebycreatingtheobjectview
SQL>createviewstudent_ov(no,stud_info)asselectno,stud(name,addr(hno,city))fromstudent
4. Nowyoucaninsertdataintostudenttableintwoways
a. Byregularinsert
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

49/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>Insertintostudentvalues(1,'sudha',111,'hyd')
b. Byusingobjectview
SQL>Insertintostudent_ovvalues(1,stud('sudha',addr(111,'hyd')))
METHODS
Youcandefinemethodswhicharenothingbutfunctionsintypesandapplyinthetableswhichholdsthe
types
Ex:
1. Definingmethodsintypes
SQL>Createtypestudasobject(namevarchar(10),marksnumber(3),Memberfunctionmakrs_f(marksin
number)returnnumber,Pragmarestrict_references(marks_f,wnds,rnds,wnps,fnps))/
2. Definingtypebody
SQL>CreatetypebodystudasMemberfunctionmarks_f(marksinnumber)returnnumberisBegin
Return(marks+100)Endmarks_fEnd/
3. Createatableusingstudtype
SQL>Createtablestudent(nonumber(2),infostud)
4. Insertsomedataintostudenttable
SQL>Insertintostudentvalues(1,stud('sudha',100))
5. Usingmethodinselect
SQL>Selects.info.marks_f(s.info.marks)fromstudents
Hereweareusingthepragmarestrict_referencestoavoidthewritestothedatabase.
VARRAYSANDNESTEDTABLES
VARRAYS
Avaryingarrayallowsyoutostorerepeatingattributesofarecordinasinglerowbutwithlimit.
Ex:
1. Wecancreatevarraysusingoracletypesaswellasuserdefinedtypes.
a. Varrayusingpredefinedtypes
SQL>Createtypevaasvarray(5)ofvarchar(10)/
b. Varraysusinguserdefinedtypes
SQL>Createtypeaddrasobject(hnonumber(3),cityvarchar(10))/
SQL>Createtypevaasvarray(5)ofaddr/
2. Usingvarrayintable
SQL>Createtablestudent(nonumber(2),namevarchar(10),addressva)
3. Insertingvaluesintovarraytable
SQL>Insertintostudentvalues(1,'sudha',va(addr(111,'hyd')))
SQL>Insertintostudentvalues(2,'jagan',va(addr(111,'hyd'),addr(222,'bang')))
4. Selectingdatafromvarraytable
SQL>Select*fromstudent
Thiswilldisplayvarraycolumndataalongwithvarrayandadt
SQL>Selectno,name,s.*fromstudents1,table(s1.address)sThiswilldisplayingeneralformat
5. Insteadofs.*youcanspecifythecolumnsinvarray
SQL>Selectno,name,s.hno,s.cityfromstudents1,table(s1.address)sUpdateanddeletenotpossible
invarrays.
Hereweusedtablefunctionwhichwilltakethevarraycolumnasinputforproducingoutputexcluding
varrayandtypes.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

5 0/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

NESTEDTABLES
Anestedtableis,asitsnameimplies,atablewithinatable.
Inthiscaseitisatablethatisrepresentedasacolumnwithinanothertable.
Nestedtablehasthesameeffectofvarraysbuthasnolimit.
Ex:
1. Wecancreatenestedtablesusingoracletypesanduserdefinedtypeswhichhasnolimit
a. Nestedtablesusingpredefinedtypes
SQL>Createtypentastableofvarchar(10)/
b. Nestedtablesusinguserdefinedtypes
SQL>Createtypeaddrasobject(hnonumber(3),cityvarchar(10))/
SQL>Createtypentastableofaddr/
2. Usingnestedtableintable
SQL>Createtablestudent(nonumber(2),namevarchar(10),addressnt)nestedtableaddressstoreas
student_temp
3. Insertingvaluesintotablewhichhasnestedtable
SQL>Insertintostudentvalues(1,'sudha',nt(addr(111,'hyd')))
SQL>Insertintostudentvalues(2,'jagan',nt(addr(111,'hyd'),addr(222,'bang')))
4. Selectingdatafromtablewhichhasnestedtable
SQL>Select*fromstudent
Thiswilldisplaynestedtablecolumndataalongwithnestedtableandadt
SQL>Selectno,name,s.*fromstudents1,table(s1.address)s
Thiswilldisplayingeneralformat
5. Insteadofs.*youcanspecifythecolumnsinnestedtable
SQL>Selectno,name,s.hno,s.cityfromstudents1,table(s1.address)s
6. Insertingnestedtabledatatotheexistingrow
SQL>Insertintotable(selectaddressfromstudentwhereno=1)values(addr(555,'chennai'))
7. Updateinnestedtables
SQL>Updatetable(selectaddressfromstudentwhereno=2)ssets.city='bombay'wheres.hno=222
8. Deleteinnestedtable
SQL>Deletetable(selectaddressfromstudentwhereno=3)swheres.hno=333
DATAMODEL
ALL_COLL_TYPES
ALL_TYPES
DBA_COLL_TYPES
DBA_TYPES
USER_COLL_TYPES
USER_TYPES
FLASHBACKQUERY
Usedtoretrievethedatawhichhasbeenalreadycommittedwithoutgoingforrecovery.Flashbacksareof
twotypes
Timebaseflashback
SCNbasedflashback(SCNstandsforSystemChangeNumber)
Ex:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

5 1/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

1. Usingtimebasedflashback
a. SQL>Select*fromstudent
Thiswilldisplayalltherows
b. SQL>Deletestudent
c. SQL>Committhiswillcommitthework.
d. SQL>Select*fromstudent
Hereitwilldisplaynothing
e. Thenexecutethefollowingprocedures
SQL>Execdbms_flashback.enable_at_time(sysdate2/1440)
f. SQL>Select*fromstudent
Hereitwilldisplaythelostdata
Thelostdatawillcomebutthecurrentsystemtimewasused
g. SQL>Execdbms_flashback.disable
Herewehavetodisabletheflashbacktoenableitagain
2. UsingSCNbasedflashback
a. DeclareavariabletostoreSCN
SQL>Variablesnumber
b. GettheSCN
SQL>Exec:s:=execdbms_flashback.get_system_change_number
c. ToseetheSCN
SQL>Prints
d. Thenexecutethefollowingprocedures
SQL>Execdbms_flashback.enable_at_system_change_number(:s)
SQL>Execdbms_flashback.disable
EXTERNALTABLES
Youcanuserexternaltablefeaturetoaccessexternalfilesasiftheyaretablesinsidethedatabase.
Whenyoucreateanexternaltable,youdefineitsstructureandlocationwithinoracle.
Whenyouquerythetable,oraclereadstheexternaltableandreturnstheresultsjustasifthedatahadbeen
storedwithinthedatabase.
ACCESSINGEXTERNALTABLEDATA
Toaccessexternalfilesfromwithinoracle,youmustfirstusethecreatedirectorycommandtodefinea
directoryobjectpointingtotheexternalfilelocation
whowillaccesstheexternalfilesmusthavethereadandwriteprivilegeonthedirectory.
Ex:
CREATINGDIRECTORYANDOSLEVELFILE
SQL>
SQLplussystem/manager
SQL>Createdirectorysaketh_diras'/Visdb/visdb/9.2.0/external'
SQL>Grantallondirectorysaketh_dirtosaketh
SQL>Connsaketh/saketh
SQL>Spooldept.lst
SQL>Selectdeptno||','||dname||','||locfromdept
SQL>Spooloff
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

5 2/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

CREATINGEXTERNALTABLE
SQL>Createtabledept_ext(deptnonumber(2),Dnamevarchar(14),Locvarchar(13))Organizationexternal
typeoracle_loaderDefaultdirectorysaketh_dirAccessparameters(recordsdelimitedbynewlineFields
terminatedby","(deptnonumber(2),Dnamevarchar(14),Locvarchar(13)))Location
('/Visdb/visdb/9.2.0/dept.lst'))
SELECTINGDATAFROMEXTERNALTABLE
SQL>select*fromdept_ext
Thiswillreadfromdept.lstwhichisaoperatingsystemlevelfile.
LIMITATIONSONEXTERNALTABLES
a. Youcannotperforminsert,update,anddeleteoperations
b. Indexingnotpossible
c. Constraintsnotpossible
BENEFITSOFEXTERNALTABLES
a. Queriesofexternaltablescompleteveryquicklyeventhoughafulltablescanidrequiredwitheachaccess
b. Youcanjoinexternaltablestoeachotherortostandardtables
REFDEREFVALUE
REF
Thereffunctionallowsreferencingofexistingrowobjects.
Eachoftherowobjectshasanobjectidvalueassignedtoit.
Theobjectidassignedcanbeseenbyusingreffunction.
DEREF
Thedereffunctionperformsoppositeaction.
Ittakesareferencevalueofobjectidandreturnsthevalueoftherowobjects.
VALUE
Eventhoughtheprimarytableisobjecttable,stillitdisplaystherowsingeneralformat.
Todisplaytheentirestructureoftheobject,thiswillbeused.
Ex:
1. createvendot_adttype
SQL>Createtypevendor_adtasobject(vendor_codenumber(2),vendor_namevarchar(2),
vendor_addressvarchar(10))/
2. createobjecttablesvendorsandvendors1
SQL>Createtablevendorsofvendor_adt
SQL>Createtablevendors1ofvendor_adt
3. insertthedataintoobjecttables
SQL>insertintovendorsvalues(1,'a','hyd')
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

5 3 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>insertintovendorsvalues(2,'b','bang')
SQL>insertintovendors1values(3,'c','delhi')
SQL>insertintovendors1values(4,'d','chennai')
4. createanothertableorderswhichholdsthevendor_adttypealso.
SQL>Createtableorders(order_nonumber(2),vendor_inforefvendor_adt)Or
SQL>Createtableorders(order_nonumber(2),vendor_inforefvendor_adtwithrowid)
5. insertthedataintoorderstable
Thevendor_infocolumninthefollowingsyntaxeswillstoreobjectidofanytablewhichisreferencedby
vendor_adtobject(bothvendorsandvendors1).
SQL>insertintoordersvalues(11,(selectref(v)fromvendorsvwherevendor_code=1))
SQL>insertintoordersvalues(12,(selectref(v)fromvendorsvwherevendor_code=2))
SQL>insertintoordersvalues(13,(selectref(v1)fromvendors1v1wherevendor_code=1))
SQL>insertintoordersvalues(14,(selectref(v1)fromvendors1v1wherevendor_code=1))
6. Toseetheobjectidsofvendortable
SQL>Selectref(V)fromvendorsv
7. Ifyouseethevendor_infoofordersitwillshowonlytheobjectidsnotthevalues,toseethevalues
SQL>Selectderef(o.vendor_info)fromorderso
8. Eventhoughthevendorstableisobjecttableitwillnotshowtheadtalongwithdata,toseethedataalong
withtheadt
SQL>Select*fromvendors
Thiswillgivethedatawithoutadt.
SQL>Selectvalue(v)fromvendorsv
Thiswillgivethecolumnsdataalongwihthetype.
REFCONSTRAINTS
Refcanalsoactsasconstraint.
Eventhoughvendors1alsoholdingvendor_adt,theorderstablewillstoretheobjectidsofvendorsonly
becauseitisconstrainedtothattableonly.
Thevendor_infocolumninthefollowingsyntaxeswillstoreobjectidsofvendorsonly.
SQL>Createtableorders(order_nonumber(2),vendor_inforefvendor_adtscopeisvendors)
Or
SQL>Createtableorders(order_nonumber(2),vendor_inforefvendor_adtconstraintfkreferencesvendors)
OBJECTVIEWSWITHREFERENCES
Toimplementtheobjectsandtherefconstraintstotheexistingtables,whatwecando?Simplydropthe
bothtablesandrecreatewithobjectsandrefconstrains.
Butyoucanachievethiswithoutdroppingthetablesandwithoutlosingthedatabycreatingobjectviews
withreferences.
Ex:
Createthefollowingtables
SQL>Createtablestudent1(nonumber(2)primarykey,namevarchar(2),marksnumber(3))
SQL>Createtablestudent2(nonumber(2)primarykey,hnonumber(3),cityvarchar(10),id
number(2),foreignKey(id)referencesstudent1(no))
Inserttherecordsintobothtables
SQL>insertintostudent1(1,'a',100)
SQL>insertintostudent1(2,'b',200)
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

5 4/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>insertintostudent2(11,111,'hyd',1)
SQL>insertintostudent2(12,222,'bang',2)
SQL>insertintostudent2(13,333,'bombay',1)
Createthetype
SQL>createorreplacetypestudasobject(nonumber(2),namevarchar(2),marksnumber(3))/
GeneratingOIDs
SQL>Createorreplaceviewstudent1_ovofstudwithobjectidentifier(orid)(no)asSelect*from
Student1
Generatingreferences
SQL>Createorreplaceviewstudent2_ovasselectno,hno,city,make_ref(student1_ov,id)idfrom
Student2
Querythefollowing
SQL>select*fromstudent1_ov
SQL>selectref(s)fromstudent1_ovs
SQL>selectvalues(s)fromstudent1_ov
SQL>select*fromstudent2_ov
SQL>selectderef(s.id)fromstudent2_ovs
PARTITIONS
Asinglelogicaltablecanbesplitintoanumberofphysicallyseparatepiecesbasedonrangesofkey
values.Eachofthepartsofthetableiscalledapartition.
Anonpartitionedtablecannotbepartitionedlater.
TYPES
Rangepartitions
Listpartitions
Hashpartitions
Subpartitions
ADVANTAGES
Reducingdowntimeforscheduledmaintenance,whichallowsmaintenanceoperationstobecarriedouton
selectedpartitionswhileotherpartitionsareavailabletousers.
Reducingdowntimeduetodatafailure,failureofaparticularpartitionwillnowayaffectotherpartitions.
Partitionindependenceallowsforconcurrentuseofthevariouspartitionsforvariouspurposes.
ADVANTAGESOFPARTITIONSBYSTORINGTHEMINDIFFERENTTABLESPACES
Reducesthepossibilityofdatacorruptioninmultiplepartitions.
Backupandrecoveryofeachpartitioncanbedoneindependently.
DISADVANTAGES
Partitionedtablescannotcontainanycolumnswithlongorlongrawdatatypes,LOBtypesorobjecttypes.
RANGEPARTITIONS
a. Creatingrangepartitionedtable
SQL>Createtablestudent(nonumber(2),namevarchar(2))partitionbyrange(no)(partitionp1valuesless
than(10),partitionp2valueslessthan(20),partitionp3valueslessthan(30),partitionp4valuesless
than(maxvalue))
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

5 5 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

**ifyouareusingmaxvalueforthelastpartition,youcannotaddapartition.
b. Insertingrecordsintorangepartitionedtable
SQL>Insertintostudentvalues(1,'a')thiswillgotop1
SQL>Insertintostudentvalues(11,'b')thiswillgotop2
SQL>Insertintostudentvalues(21,'c')thiswillgotop3
SQL>Insertintostudentvalues(31,'d')thiswillgotop4
c. Retrievingrecordsfromrangepartitionedtable
SQL>Select*fromstudent
SQL>Select*fromstudentpartition(p1)
d. Possibleoperationswithrangepartitions
Add
Drop
Truncate
Rename
Split
Move
Exchange
e. Addingapartition
SQL>Altertablestudentaddpartitionp5valueslessthan(40)
f. Droppingapartition
SQL>Altertablestudentdroppartitionp4
g. Renamingapartition
SQL>Altertablestudentrenamepartitionp3top6
h. Truncateapartition
SQL>Altertablestudenttruncatepartitionp6
i. Splittingapartition
SQL>Altertablestudentsplitpartitionp2at(15)into(partitionp21,partitionp22)
j. Exchangingapartition
SQL>Altertablestudentexchangepartitionp1withtablestudent2
k. Movingapartition
SQL>Altertablestudentmovepartitionp21tablespacesaketh_ts
LISTPARTITIONS
1. Creatinglistpartitionedtable
SQL>Createtablestudent(nonumber(2),namevarchar(2))partitionbylist(no)(partitionp1
values(1,2,3,4,5),partitionp2values(6,7,8,9,10),partitionp3values(11,12,13,14,15),partitionp4
values(16,17,18,19,20))
2. Insertingrecordsintolistpartitionedtable
SQL>Insertintostudentvalues(1,'a')thiswillgotop1
SQL>Insertintostudentvalues(6,'b')thiswillgotop2
SQL>Insertintostudentvalues(11,'c')thiswillgotop3
SQL>Insertintostudentvalues(16,'d')thiswillgotop4
3. Retrievingrecordsfromlistpartitionedtable
SQL>Select*fromstudent
SQL>Select*fromstudentpartition(p1)
4. Possibleoperationswithlistpartitions
Add
Drop
Truncate
Rename
Move
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

5 6/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Exchange
5. Addingapartition
SQL>Altertablestudentaddpartitionp5values(21,22,23,24,25)
6. Droppingapartition
SQL>Altertablestudentdroppartitionp4
7. Renamingapartition
SQL>Altertablestudentrenamepartitionp3top6
8. Truncateapartition
SQL>Altertablestudenttruncatepartitionp6
9. Exchangingapartition
SQL>Altertablestudentexchangepartitionp1withtablestudent2
10. Movingapartition
SQL>Altertablestudentmovepartitionp2tablespacesaketh_ts
HASHPARTITIONS
a. Creatinghashpartitionedtable
SQL>Createtablestudent(nonumber(2),namevarchar(2))partitionbyhash(no)partitions5
Hereoracleautomaticallygivespartitionnameslike
SYS_P1
SYS_P2
SYS_P3
SYS_P4
SYS_P5
b. Insertingrecordsintohashpartitionedtableitwillinserttherecordsbasedonhashfunctioncalculatedby
takingthepartitionkey
SQL>Insertintostudentvalues(1,'a')
SQL>Insertintostudentvalues(6,'b')
SQL>Insertintostudentvalues(11,'c')
SQL>Insertintostudentvalues(16,'d')
c. Retrievingrecordsfromhashpartitionedtable
SQL>Select*fromstudent
SQL>Select*fromstudentpartition(sys_p1)
d. Possibleoperationswithhashpartitions
Add
Truncate
Rename
Move
Exchange
e. Addingapartition
SQL>Altertablestudentaddpartitionp6
f. Renamingapartition
SQL>Altertablestudentrenamepartitionp6top7
g. Truncateapartition
SQL>Altertablestudenttruncatepartitionp7
h. Exchangingapartition
SQL>Altertablestudentexchangepartitionsys_p1withtablestudent2
i. Movingapartition
SQL>Altertablestudentmovepartitionsys_p2tablespacesaketh_ts
SUBPARTITIONSWITHRANGEANDHASH
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

5 7/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Subpartitionsclauseisusedbyhashonly.
Wecannotcreatesubpartitionswithlistandhashpartitions.
1. Creatingsubpartitionedtable
SQL>Createtablestudent(nonumber(2),namevarchar(2),marksnumber(3))Partitionbyrange(no)
subpartitionbyhash(name)subpartitions3(Partitionp1valueslessthan(10),partitionp2valuesless
than(20))
Thiswillcreatetwopartitionsp1andp2withthreesubpartitionsforeachpartition
P1 P2 -

SYS_SUBP1
SYS_SUBP2
SYS_SUBP3
SYS_SUBP4
SYS_SUBP5
SYS_SUBP6

**ifyouareusingmaxvalueforthelastpartition,youcannotaddapartition.
2. Insertingrecordsintosubpartitionedtable
SQL>Insertintostudentvalues(1,'a')thiswillgotop1
SQL>Insertintostudentvalues(11,'b')thiswillgotop2
3. Retrievingrecordsfromsubpartitionedtable
SQL>Select*fromstudent
SQL>Select*fromstudentpartition(p1)
SQL>Select*fromstudentsubpartition(sys_subp1)
4. Possibleoperationswithsubpartitions
Add
Drop
Truncate
Rename
Split
5. Addingapartition
SQL>Altertablestudentaddpartitionp3valueslessthan(30)
6. Droppingapartition
SQL>Altertablestudentdroppartitionp3
7. Renamingapartition
SQL>Altertablestudentrenamepartitionp2top3
8. Truncateapartition
SQL>Altertablestudenttruncatepartitionp1
9. Splittingapartition
SQL>Altertablestudentsplitpartitionp3at(15)into(partitionp31,partitionp32)
DATAMODEL
ALL_IND_PARTITIONS
ALL_IND_SUBPARTITIONS
ALL_TAB_PARTITIONS
ALL_TAB_SUBPARTITIONS
DBA_IND_PARTITIONS
DBA_IND_SUBPARTITIONS
DBA_TAB_PARTITIONS
DBA_TAB_SUBPARTITIONS
USER_IND_PARTITIONS
USER_IND_SUBPARTITIONS
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

5 8 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

USER_TAB_PARTITIONS
USER_TAB_SUBPARTITIONS
GROUPBYANDHAVING
GROUPBY
Usinggroupby,wecancreategroupsofrelatedinformation.
Columnsusedinselectmustbeusedwithgroupby,otherwiseitwasnotagroupbyexpression.
Ex:
SQL>selectdeptno,sum(sal)fromempgroupbydeptno
DEPTNO SUM(SAL)
---------- ---------10
8750
20
10875
30
9400

SQL>selectdeptno,job,sum(sal)fromempgroupbydeptno,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

HAVING
Thiswillworkaswhereclausewhichcanbeusedonlywithgroupbybecauseofabsenceofwhereclausein
groupby.
Ex:
SQL>selectdeptno,job,sum(sal)tsalfromempgroupbydeptno,jobhavingsum(sal)>3000
DEPTNO JOB
---------- --------10
PRESIDENT
20
ANALYST
30
SALESMAN

TSAL
---------5000
6000
5600

SQL>selectdeptno,job,sum(sal)tsalfromempgroupbydeptno,jobhavingsum(sal)>3000orderby
job
DEPTNO
JOB
---------- --------20
ANALYST
10
PRESIDENT

TSAL
---------6000
5000

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

5 9/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

30

SALESMAN

5600

ORDEROFEXECUTION
Grouptherowstogetherbasedongroupbyclause.
Calculatethegroupfunctionsforeachgroup.
Chooseandeliminatethegroupsbasedonthehavingclause.
Orderthegroupsbasedonthespecifiedcolumn.
ROLLUPGROUPINGCUBE
Thesearetheenhancementstothegroupbyfeature.
USINGROLLUP
Thiswillgivethesalariesineachdepartmentineachjobcategoryalongwihthetotalsalaryfotindividual
departmentsandthetotalsalaryofallthedepartments.
SQL>Selectdeptno,job,sum(sal)fromempgroupbyrollup(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

USINGGROUPING
Intheabovequeryitwillgivethetotalsalaryoftheindividualdepartmentsbutwithablankinthejobcolumn
andgivesthetotalsalaryofallthedepartmentswithblanksindeptnoandjobcolumns.
Toreplacetheseblankswithyourdesiredstringgroupingwillbeused
SQL>selectdecode(grouping(deptno),1,'AllDepts',deptno),decode(grouping(job),1,'Alljobs',job),sum(sal)
fromempgroupbyrollup(deptno,job)
DECODE(GROUPING(DEPTNO),1,'ALLDEPTS',DEP DECODE(GR
-------------------------- ----------------------10
CLERK
10
MANAGER
10
PRESIDENT
10
All jobs
20
ANALYST
20
CLERK
20
MANAGER
20
All jobs
30
CLERK
30
MANAGER
30
SALESMAN
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

SUM(SAL)
-------------1300
2450
5000
8750
6000
1900
2975
10875
950
2850
5600
60/18 2

7/4/2016

30
All Depts

plsqlH om e Oracle , PL/SQL M at erial

All jobs
All jobs

9400
29025

Groupingwillreturn1ifthecolumnwhichisspecifiedinthegroupingfunctionhasbeenusedinrollup.
Groupingwillbeusedinassociationwithdecode.
USINGCUBE
Thiswillgivethesalariesineachdepartmentineachjobcategory,thetotalsalaryforindividualdepartments,
thetotalsalaryofallthedepartmentsandthesalariesineachjobcategory.
SQL>selectdecode(grouping(deptno),1,'AllDepts',deptno),decode(grouping(job),1,'AllJobs',job),sum(sal)
fromempgroupbycube(deptno,job)
DECODE(GROUPING(DEPTNO),1,'ALLDEPTS',DEP DECODE(GR
------------------------- -----------------------10
CLERK
10
MANAGER
10
PRESIDENT
10
All Jobs
20
ANALYST
20
CLERK
20
MANAGER
20
All Jobs
30
CLERK
30
MANAGER
30
SALESMAN
30
All Jobs
All Depts
ANALYST
All Depts
CLERK
All Depts
MANAGER
All Depts
PRESIDENT
All Depts
SALESMAN
All Depts
All Jobs

SUM(SAL)
-----------1300
2450
5000
8750
6000
1900
2975
10875
950
2850
5600
9400
6000
4150
8275
5000
5600
29025

SETOPERATORS
TYPES
Union
Unionall
Intersect
Minus
UNION
Thiswillcombinetherecordsofmultipletableshavingthesamestructure.
Ex:
SQL>select*fromstudent1unionselect*fromstudent2
UNIONALL
Thiswillcombinetherecordsofmultipletableshavingthesamestructurebutincludingduplicates.
Ex:
SQL>select*fromstudent1unionallselect*fromstudent2
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

61/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

INTERSECT
Thiswillgivethecommonrecordsofmultipletableshavingthesamestructure.
Ex:
SQL>select*fromstudent1intersectselect*fromstudent2
MINUS
Thiswillgivetherecordsofatablewhoserecordsarenotinothertableshavingthesamestructure.
Ex:
SQL>select*fromstudent1minusselect*fromstudent2
VIEWS
Aviewisadatabaseobjectthatisalogicalrepresentationofatable.Itisdeliveredfromatablebuthasno
storageofitsownandoftenmaybeusedinthesamemannerasatable.
Aviewtakestheoutputofthequeryandtreatsitasatable,thereforeaviewcanbethoughtofasastored
queryoravirtualtable.
TYPES
Simpleview
Complexview
Simpleviewcanbecreatedfromonetablewhereascomplexviewcanbecreatedfrommultipletables.
WHYVIEWS?
Providesadditionallevelofsecuritybyrestrictingaccesstoapredeterminedsetofrowsand/orcolumnsof
atable.
Hidethedatacomplexity.
Simplifycommandsfortheuser.
VIEWSWITHOUTDML
Readonlyview
Viewwithgroupby
Viewwithaggregatefunctions
Viewwithrownum
Partitionview
Viewwithdistinct
Ex:
SQL>Createviewdept_vasselect*fromdeptwithreadonly
SQL>Createviewdept_vasselectdeptno,sum(sal)t_salfromempgroupbydeptno
SQL>Createviewstudasselectrownumno,name,marksfromstudent
SQL>Createviewstudentasselect*fromstudent1unionselect*fromstudent2
SQL>Createviewstudasselectdistinctno,namefromstudent
VIEWSWITHDML
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

62/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Viewwithnotnullcolumn
insertwithoutnotnullcolumnnotpossible
updatenotnullcolumntonullisnotpossible
deletepossible
Viewwithoutnotnullcolumnwhichwasinbasetable
insertnotpossible
update,deletepossible
Viewwithexpression
insert,updatenotpossible
deletepossible
Viewwithfunctions(exceptaggregate)
insert,updatenotpossible
deletepossible
Viewwascreatedbuttheunderlyingtablewasdroppedthenwewillgetthemessagelike"viewhas
errors".
Viewwascreatedbutthebasetablehasbeenalteredbutstilltheviewwaswiththeinitialdefinition,we
havetoreplacetheviewtoaffectthechanges.
Complexview(viewwithmorethanonetable)
insertnotpossible
update,deletepossible(notalways)
CREATINGVIEWWITHOUTHAVINGTHEBASETABLE
SQL>Createforceviewstudasselect*Fromstudent
Oncethebasetablewascreatedthentheviewisvalidated.
VIEWWITHCHECKOPTIONCONSTRAINT
SQL>Createviewstudasselect*fromstudentwheremarks=500withcheckoptionconstraintCk
Insertpossiblewithmarksvalueas500
Updatepossibleexcludingmarkscolumn
Deletepossible
DROPPINGVIEWS
SQL>dropviewdept_v
SYNONYMANDSEQUENCE
SYNONYM
Asynonymisadatabaseobject,whichisusedasanaliasforatable,vieworsequence.
TYPES
Private
Public
Privatesynonymisavailabletotheparticularuserwhocreates.
PublicsynonymiscreatedbyDBAwhichisavailabletoalltheusers.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

63 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

ADVANTAGES
Hidethenameandowneroftheobject.
Provideslocationtransparencyforremoteobjectsofadistributeddatabase.
CREATEANDDROP
SQL>createsynonyms1foremp
SQL>createpublicsynonyms2foremp
SQL>dropsynonyms1
SEQUENCE
Asequenceisadatabaseobject,whichcangenerateunique,sequentialintegervalues.
Itcanbeusedtoautomaticallygenerateprimarykeyoruniquekeyvalues.
Asequencecanbeeitherinanascendingordescendingorder.
Syntax:
Createsequence<seq_name>[incrementbtyn][startwithn][maxvaluen][minvaluen][cycle/nocycle]
[cache/nocache]
Bydefalultthesequencestartswith1,incrementsby1withminvalueof1andwithnocycle,nocache.
Cacheoptionprealloocatesasetofsequencenumbersandretainstheminmemoryforfasteraccess.
Ex:
SQL>createsequences
SQL>createsequencesincrementby10startwith100minvalue5maxvalue200cyclecache20
USINGSEQUENCE
SQL>createtablestudent(nonumber(2),namevarchar(10))
SQL>insertintostudentvalues(s.nextval,'saketh')
Initiallycurrvalisnotdefinedandnextvalisstartingvalue.
Afterthatnextvalandcurrvalarealwaysequal.
CREATINGALPHANUMERICSEQUENCE
SQL>createsequencesstartwith111234
SQL>Insertintostudentvalues(s.nextval||translate(s.nextval,'1234567890','abcdefghij'))
ALTERINGSEQUENCE
Wecanalterthesequencetoperformthefollowing.
Setoreliminateminvalueormaxvalue.
Changetheincrementvalue.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

64/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Changethenumberofcachedsequencenumbers.
Ex:
SQL>altersequencesminvalue5
SQL>altersequencesincrementby2
SQL>altersequencescache10
DROPPINGSEQUENCE
SQL>dropsequences
JOINS
Thepurposeofajoinistocombinethedataacrosstables.
Ajoinisactuallyperformedbythewhereclausewhichcombinesthespecifiedrowsoftables.
Ifajoininvolvesinmorethantwotablesthenoraclejoinsfirsttwotablesbasedonthejoinsconditionand
thencomparestheresultwiththenexttableandsoon.
TYPES
Equijoin
Nonequijoin
Selfjoin
Naturaljoin
Crossjoin
Outerjoin
Leftouter
Rightouter
Fullouter
Innerjoin
Usingclause
Onclause
Assumethatwehavethefollowingtables.
SQL>select*fromdept
DEPTNO DNAME
LOC
------ ---------- ---------10
mkt
hyd
20
fin
bang
30
hr
bombay

SQL>select*fromemp
EMPNO
-----111
222

ENAME
JOB
MGR
DEPTNO
---------- ---------- ---------- ---------saketh
analyst 444
10
sudha
clerk
333
20

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

65 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

333
444

jagan
madhu

manager 111
engineer 222

10
40

EQUIJOIN
Ajoinwhichcontainsan'='operatorinthejoinscondition.
Ex:
SQL>selectempno,ename,job,dname,locfromempe,deptdwheree.deptno=d.deptno
EMPNO
-----111
333
222

ENAME
JOB
DNAME
LOC
--------- ------- ---------- ---------saketh
analyst
mkt
hyd
jagan
manager
mkt
hyd
sudha
clerk
fin
bang

USINGCLAUSE
SQL>selectempno,ename,job,dname,locfromempejoindeptdusing(deptno)
EMPNO ENAME
JOB
DNAME
LOC
------- ---------- -------- ---------- ---------111
saketh
analyst
mkt
hyd
333
jagan
manager
mkt
hyd
222
sudha
clerk
fin
bang

ONCLAUSE
SQL>selectempno,ename,job,dname,locfromempejoindeptdon(e.deptno=d.deptno)
EMPNO ENAME
JOB
DNAME
LOC
------ ---------- -------- ---------- ------111
saketh
analyst
mkt
hyd
333
jagan
manager
mkt
hyd
222
sudha
clerk
fin
bang

NONEQUIJOIN
Ajoinwhichcontainsanoperatorotherthan'='inthejoinscondition.
Ex:
SQL>selectempno,ename,job,dname,locfromempe,deptdwheree.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

SELFJOIN
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

66/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Joiningthetableitselfiscalledselfjoin.
Ex:
SQL>selecte1.empno,e2.ename,e1.job,e2.deptnofromempe1,empe2wheree1.empno=e2.mgr
EMPNO
-----111
222
333
444

ENAME
-------jagan
madhu
sudha
saketh

JOB
DEPTNO
------- -------analyst
10
clerk
40
manager
20
engineer 10

NATURALJOIN
Naturaljoincomparesallthecommoncolumns.
Ex:
SQL>selectempno,ename,job,dname,locfromempnaturaljoindept
EMPNO
ENAME
JOB
DNAME
---------- ---------- ---------- -----111
saketh
analyst
mkt
333
jagan
manager
mkt
222
sudha
clerk
fin

LOC
-------hyd
hyd
bang

CROSSJOIN
Thiswillgivesthecrossproduct.
Ex:
SQL>selectempno,ename,job,dname,locfromempcrossjoindept
EMPNO
------111
222
333
444
111
222
333
444
111
222
333
444

ENAME
JOB
DNAME
------- ---------- ------saketh analyst
mkt
sudha
clerk
mkt
jagan
manager
mkt
madhu
engineer
mkt
saketh analyst
fin
sudha
clerk
fin
jagan
manager
fin
madhu
engineer
fin
saketh analyst
hr
sudha
clerk
hr
jagan
manager
hr
madhu
engineer
hr

LOC
-----hyd
hyd
hyd
hyd
bang
bang
bang
bang
bombay
bombay
bombay
bombay

OUTERJOIN
Outerjoingivesthenonmatchingrecordsalongwithmatchingrecords.
LEFTOUTERJOIN
Thiswilldisplaytheallmatchingrecordsandtherecordswhichareinlefthandsidetablethosethatarenotin
righthandsidetable.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

67/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Ex:
SQL>selectempno,ename,job,dname,locfromempeleftouterjoindeptdon(e.deptno=d.deptno)
Or
SQL>selectempno,ename,job,dname,locfromempe,deptdwheree.deptno=d.deptno(+)
EMPNO
-------111
333
222
444

ENAME
JOB
DNAME
LOC
-------- -------- -------- -----saketh
analyst
mkt
hyd
jagan
manager
mkt
hyd
sudha
clerk
fin
bang
madhu
engineer

RIGHTOUTERJOIN
Thiswilldisplaytheallmatchingrecordsandtherecordswhichareinrighthandsidetablethosethatarenot
inlefthandsidetable.
Ex:
SQL>selectempno,ename,job,dname,locfromemperightouterjoindeptdon(e.deptno=d.deptno)
Or
SQL>selectempno,ename,job,dname,locfromempe,deptdwheree.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

FULLOUTERJOIN
Thiswilldisplaytheallmatchingrecordsandthenonmatchingrecordsfrombothtables.
Ex:
SQL>selectempno,ename,job,dname,locfromempefullouterjoindeptdon(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

INNERJOIN
Thiswilldisplayalltherecordsthathavematched.
Ex:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

68 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>selectempno,ename,job,dname,locfromempinnerjoindeptusing(deptno)
EMPNO
ENAME JOB
DNAME
LOC
------ -------- -------- -------- -------111
saketh analyst
mkt
hyd
333
jagan manager
mkt
hyd
222
sudha clerk
fin
bang

SUBQUERIESANDEXISTS
SUBQUERIES
Nestingofqueries,onewithintheotheristermedasasubquery.
Astatementcontainingasubqueryiscalledaparentquery.
Subqueriesareusedtoretrievedatafromtablesthatdependonthevaluesinthetableitself.
TYPES
Singlerowsubqueries
Multirowsubqueries
Multiplesubqueries
Correlatedsubqueries
SINGLEROWSUBQUERIES
Insinglerowsubquery,itwillreturnonevalue.
Ex:
SQL>select*fromempwheresal>(selectsalfromempwhereempno=7566)
EMPNO
ENAME
---------- -----7788
SCOTT
7839
KING
7902
FORD

JOB
MGR
HIREDATE
SAL COMM
--------- ------- ---------- ----- -----ANALYST
7566 19-APR-87
3000
PRESIDENT
17-NOV-81
5000
ANALYST
7566 03-DEC-81
3000

DEPTNO
-------20
10
20

MULTIROWSUBQUERIES
Inmultirowsubquery,itwillreturnmorethanonevalue.
Insuchcasesweshouldincludeoperatorslikeany,all,inornotinbetweenthecomparisionoperatorand
thesubquery.
Ex:
SQL>select*fromempwheresal>any(selectsalfromempwheresalbetween2500and4000)
EMPNO
-----7566
7788
7839
7902

ENAME
------JONES
SCOTT
KING
FORD

JOB
MGR
HIREDATE SAL COMM
DEPTNO
------- ------ ---------- ------ ------ --------MANAGER 7839 02-APR-81 2975
20
ANALYST 7566 19-APR-87 3000
20
PRESIDENT
17-NOV-81 5000
10
ANALYST 7566 03-DEC-81 3000
20

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

69/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>select*fromempwheresal>all(selectsalfromempwheresalbetween2500and4000)
EMPNO
-----7839

ENAME
JOB
MGR
------- --------- ----KING
PRESIDENT

HIREDATE
---------17-NOV-81

SAL
COMM DEPTNO
------ ----- ------5000
10

MULTIPLESUBQUERIES
Thereisnolimitonthenumberofsubqueriesincludedinawhereclause.
Itallowsnestingofaquerywithinasubquery.
Ex:
SQL>select*fromempwheresal=(selectmax(sal)fromempwheresal<(selectmax(sal)fromemp))
EMPNO
ENAME JOB
MGR
HIREDATE SAL COMM
---------- ------ -------- ---------- --------- ----- ----7788
SCOTT ANALYST 7566
19-APR-87 3000
7902
FORD
ANALYST 7566
03-DEC-81 3000

DEPTNO
------20
20

CORRELATEDSUBQUERIES
Asubqueryisevaluatedoncefortheentireparentstatementwhereasacorrelatedsubqueryisevaluatedonce
foreveryrowprocessedbytheparentstatement.
Ex:
SQL>selectdistinctdeptnofromempewhere5<=(selectcount(ename)fromempwheree.deptno=
deptno)
DEPTNO
-------20
30

EXISTS
Existsfunctionisatestforexistence.Thisisalogicaltestforthereturnofrowsfromaquery.
Ex:
Supposewewanttodisplaythedepartmentnumberswhichhasmorethan4employees.
SQL>selectdeptno,count(*)fromempgroupbydeptnohavingcount(*)>4
DEPTNO
--------20
30

COUNT(*)
---------5
6

Fromtheabovequerycanyouwanttodisplaythenamesofemployees?
SQL>selectdeptno,ename,count(*)fromempgroupbydeptno,enamehavingcount(*)>4
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

70/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

no rows selected

Theabovequeryreturnsnothingbecausecombinationofdeptnoandenameneverreturnmorethanonecount.
Thesolutionistouseexistswhichfollows.
SQL>selectdeptno,enamefromempe1whereexists(select*fromempe2wheree1.deptno=e2.deptno
groupbye2.deptnohavingcount(e2.ename)>4)orderbydeptno,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

NOTEXISTS
SQL>selectdeptno,enamefromempe1wherenotexists(select*fromempe2where
e1.deptno=e2.deptnogroupbye2.deptnohavingcount(e2.ename)>4)orderbydeptno,ename
DEPTNO
ENAME
--------- ---------10
CLARK
10
KING
10
MILLER

WALKUPTREESANDINLINEVIEW
WALKUPTREES
Usinghierarchicalqueries,youcanretrievedatabasedonanaturalhierarchicalrelationshipbetweenrowsina
table.However,whereahierarchicalrelationshipexistsbetweentherowsofatable,aprocesscalledtree
walkingenablesthehierarchytobeconstructed.
Ex:
SQL>selectename||'==>'||priorename,levelfromempstartwithename='KING'connectbyprior
empno=mgr

ENAME||'==>'||PRIORENAM
-----------------------KING==>
JONES==>KING
SCOTT==>JONES
ADAMS==>SCOTT
FORD==>JONES

LEVEL
-------1
2
3
4
3

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

71/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SMITH==>FORD
BLAKE==>KING
ALLEN==>BLAKE
WARD==>BLAKE
MARTIN==>BLAKE
TURNER==>BLAKE
JAMES==>BLAKE
CLARK==>KING
MILLER==>CLARK

4
2
3
3
3
3
3
2
3

IntheaboveStartwithclausespecifiestherootrowofthetable.
Levelpseudocolumngivesthe1forroot,2forchildandsoon.
Connectbypriorclausespecifiesthecolumnswhichhasparentchildrelationship.
INLINEVIEWORTOPNANALYSIS
Intheselectstatementinsteadoftablename,replacingtheselectstatementisknownasinlineview.
Ex:
SQL>Selectename,sal,rownumrankfrom(select*fromemporderbysal)
ENAME
------SMITH
JAMES
ADAMS
WARD
MARTIN
MILLER
TURNER
ALLEN
CLARK
BLAKE
JONES
SCOTT
FORD
KING

SAL
RANK
---------- ------800
1
950
2
1100
3
1250
4
1250
5
1300
6
1500
7
1600
8
2450
9
2850
10
2975
11
3000
12
3000
13
5000
14

LOCKS
Locksarethemechanismsusedtopreventdestructiveinteractionbetweenusersaccessingsameresource
simultaneously.
Locksprovideshighdegreeofdataconcurrency.
TYPES
Rowlevellocks
Tablelevellocks
ROWLEVELLOCKS
Intherowlevellockarowislockedexclusivelysothatothercannotmodifytherowuntilthetransaction
holdingthelockiscommittedorrolledback.
Thiscanbedonebyusingselect..forupdateclause.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

72/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Ex:
SQL>select*fromempwheresal>3000forupdateofcomm.
TABLELEVELLOCKS
Atablelevellockwillprotecttabledatatherebyguaranteeingdataintegritywhendataisbeingaccessed
concurrentlybymultipleusers.
Atablelockcanbeheldinseveralmodes.
Sharelock
Shareupdatelock
Exclusivelock
SHARELOCK
Asharelocklocksthetableallowingotheruserstoonlyquerybutnotinsert,updateordeleterowsina
table.
Multipleuserscanplacesharelocksonthesameresourceatthesametime.
Ex:
SQL>locktableempinsharemode
SHAREUPDATELOCK
Itlocksrowsthataretobeupdatedinatable.
Itpermitsotheruserstoconcurrentlyquery,insert,updateorevenlockotherrowsinthesametable.
Itpreventstheotherusersfromupdatingtherowthathasbeenlocked.
Ex:
SQL>locktableempinshareupdatemode
EXCLUSIVELOCK
Exclusivelockisthemostrestrictiveoftableslocks.
Whenissuedbyanyuser,itallowstheotherusertoonlyquery.
Itissimilartosharelockbutonlyoneusercanplaceexclusivelockonatableatatime.
Ex:
SQL>locktableempinshareexclusivemode
NOWAIT
Ifoneuserlockedthetablewithoutnowaitthenanotherusertryingtolockthesametablethenhehasto
waituntiltheuserwhohasinitiallylockedthetableissuesacommitorrollbackstatement.
Thisdelaycouldbeavoidedbyappendinganowaitclauseinthelocktablecommand.
Ex:
SQL>locktableempinexclusivemodenowait.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

73 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

DEADLOCK
Adeadlockoccurswhentowusershavealockeachonseparateobject,andtheywanttoacquirealockon
theeachother'sobject.
Whenthishappens,thefirstuserhastowaitforthesecondusertoreleasethelock,buttheseconduser
willnotreleaseituntilthelockonthefirstuser'sobjectisfreed.
Insuchacase,oracledetectsthedeadlockautomaticallyandsolvestheproblembyabortingoneofthetwo
transactions.
INDEXES
Indexistypicallyalistingofkeywordsaccompaniedbythelocationofinformationonasubject.
WecancreateindexesexplicitlytospeedupSQLstatementexecutiononatable.
Theindexpointsdirectlytothelocationoftherowscontainingthevalue.
WHYINDEXES?
Indexesaremostusefulonlargertables,oncolumnsthatarelikelytoappearinwhereclausesassimple
equality.
TYPES
Uniqueindex
Nonuniqueindex
Btreeindex
Bitmapindex
Compositeindex
Reversekeyindex
Functionbasedindex
Descendingindex
Domainindex
Objectindex
Clusterindex
Textindex
Indexorganizedtable
Partitionindex
Localindex
Localprefixed
Localnonprefixed
Globalindex
Globalprefixed
Globalnonprefixed
UNIQUEINDEX
Uniqueindexesguaranteethatnotworowsofatablehaveduplicatevaluesinthecolumnsthatdefinethe
index.
Uniqueindexisautomaticallycreatedwhenprimarykeyoruniqueconstraintiscreated.
Ex:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

74/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>createuniqueindexstud_indonstudent(sno)
NONUNIQUEINDEX
NonUniqueindexesdonotimposetheaboverestrictiononthecolumnvalues.
Ex:
SQL>createindexstud_indonstudent(sno)
BTREEINDEXorASCENDINGINDEX
1. Thedefaulttypeofindexusedinanoracledatabaseisthebtreeindex.
2. Abtreeindexisdesignedtoprovidebothrapidaccesstoindividualrowsandquickaccesstogroupsof
rowswithinarange.
3. Thebtreeindexdoesthisbyperformingasuccessionofvaluecomparisons.
4. Eachcomparisoneliminatesmanyoftherows.
Ex:
SQL>createindexstud_indonstudent(sno)
BITMAPINDEX
Thiscanbeusedforlowcardinalitycolumns:thatiscolumnsinwhichthenumberofdistinctvaluesis
snallwhencomparedtothenumberoftherowsinthetable.
Ex:
SQL>createbitmapindexstud_indonstudent(sex)
COMPOSITEINDEX
Acompositeindexalsocalledaconcatenatedindexisanindexcreatedonmultiplecolumnsofatable.
Columnsinacompositeindexcanappearinanyorderandneednotbeadjacentcolumnsofthetable.
Ex:
SQL>createbitmapindexstud_indonstudent(sno,sname)
REVERSEKEYINDEX
1. Areversekeyindexwhencomparedtostandardindex,reverseseachbyteofthecolumnbeingindexed
whilekeepingthecolumnorder.
2. Whenthecolumnisindexedinreversemodethenthecolumnvalueswillbestoredinanindexin
differentblocksasthestartingvaluediffers.
3. Suchanarrangementcanhelpavoidperformancedegradationsinindexeswheremodificationstothe
indexareconcentratedonasmallsetofblocks.
Ex:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

75 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>createindexstud_indonstudent(sno,reverse)
Wecanrebuildareversekeyindexintonormalindexusingthenoreversekeyword.
Ex:
SQL>alterindexstud_indrebuildnoreverse
FUNCTIONBASEDINDEX
Thiswilluseresultofthefunctionaskeyinsteadofusingcolumnasthevalueforthekey.
Ex:
SQL>createindexstud_indonstudent(upper(sname))
DESCENDINGINDEX
1. TheorderusedbyBtreeindexeshasbeenascendingorder.
2. YoucancategorizedatainBtreeindexindescendingorderaswell.
3. Thisfeaturecanbeusefulinapplicationswheresortingoperationsarerequired.
Ex:
SQL>createindexstud_indonstudent(snodesc)
TEXTINDEX
1. Queryingtextisdifferentfromqueryingdatabecausewordshaveshadesofmeaning,relationshipsto
otherwords,andopposites.
2. Youmaywanttosearchforwordsthatareneareachother,orwordsthatarerelatedtothers.
3. Thesequerieswouldbeextremelydifficultifallyouhadavailablewasthestandardrelationaloperators.
4. ByextendingSQLtoincludetextindexes,oracletextpermitsyoutoaskverycomplexquestionsaboutthe
text.
5. Touseoracletext,youneedtocreateatextindexonthecolumninwhichthetextisstored.
6. Textindexisacollectionoftablesandindexesthatstoreinformationaboutthetextstoredinthecolumn.
TYPES
Thereareseveraldifferenttypesofindexesavailableinoracle9i.
Thefirst,CONTEXTissupportedinoracle8iaswellasoracle9i.
Asoforacle9i,youcanusetheCTXCATtextindexfofurtherenhanceyourtextindexmanagementand
querycapabilities.
CONTEXT
CTXCAT
CTXRULE
TheCTXCATindextypesupportsthetransactionalsynchronizationofdatabetweenthebasetableanditstext
index.
WithCONTEXTindexes,youneedtomanuallytelloracletoupdatethevaluesinthetextindexafterdata
changesinbasetable.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

76/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

CTXCATindextypesdonotgeneratescorevaluesduringthetextqueries.
HOWTOCREATETEXTINDEX?
Youcancreateatextindexviaaspecialversionofthecreateindexcomman.
Forcontextindex,specifythectxsys.contextindextypeandforctxcatindex,specifythectxsys.ctxcat
indextype.
Ex:
SupposeyouhaveatablecalledBOOKSwiththefollowingcolumnsTitle,Author,Info.
SQL>createindexbook_indexonbooks(info)indextypeisctxsys.context
SQL>createindexbook_indexonbooks(info)indextypeisctxsys.ctxcat
TEXTQUERIES
OnceatextindexiscreatedontheinfocolumnofBOOKStable,textsearchingcapabilitiesincrease
dynamically.
CONTAINS&CATSEARCH
CONTAINSfunctiontakestwoparametersthecolumnnameandthesearchstring.
Syntax:
Contains(indexed_column,search_str)
IfyoucreateaCTXCATindex,usetheCATSEARCHfunctioninplaceofCONTAINS.
CATSEARCHtakesthreeparametersthecolumnname,thesearchstringandtheindexset.
Syntax:
Contains(indexed_column,search_str,index_set)
HOWATEXTQEURYWORKS?
WhenafunctionsuchasCONTAINSorCATSEARCHisusedinquery,thetextportionofthequeryis
processedbyoracletext.
Theremainderofthequeryisprocessedjustlikearegularquerywithinthedatabase.
Theresultofthetextqueryprocessingandtheregularqueryprocessingaremergedtoreturnasingleset
ofrecordstotheuser.
SEARCHINGFORANEXACTMATCHOFAWORDThefollowingquerieswillsearchforaword
called'prperty'whosescoreisgreaterthanzero.
SQL>select*frombookswherecontains(info,'property')>0
SQL>select*frombookswherecatsearch(info,'property',null)>0
Supposeifyouwanttoknowthescoreofthe'property'ineachbook,ifscorevaluesforindividualsearches
rangefrom0to10foreachoccurrenceofthestringwithinthetextthenusethescorefunction.
SQL>selecttitle,score(10)frombookswherecontains(info,'property',10)>0
SEARCHINGFORANEXACTMATCHOFMULTIPLEWORDS
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

77/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Thefollowingquerieswillsearchfortwowords.
SQL>select*frombookswherecontains(info,'propertyANDharvests')>0
SQL>select*frombookswherecatsearch(info,'propertyANDharvests',null)>0
InsteadofusingANDyoucouldhaeusedanampersand(&).Beforeusingthismethod,setdefineoffso
the&characterwillnotbeseenaspartofavariablename.
SQL>setdefineoff
SQL>select*frombookswherecontains(info,'property&harvests')>0
SQL>select*frombookswherecatsearch(info,'propertyharvests',null)>0
Thefollowingquerieswillsearchformorethantwowords.
SQL>select*frombookswherecontains(info,'propertyANDharvestsANDworkers')>0
SQL>select*frombookswherecatsearch(info,'propertyharvestsworkers',null)>0
Thefollowingquerieswillsearchforeitherofthetwowords.
SQL>select*frombookswherecontains(info,'propertyORharvests')>0
InsteadofORyoucanuseaverticalline(|).
SQL>select*frombookswherecontains(info,'property|harvests')>0
SQL>select*frombookswherecatsearch(info,'property|harvests',null)>0
InthefollowingqueriestheACCUM(accumulate)operatoraddstogetherthescoresoftheindividual
searchesandcomparestheaccumulatedscoretothethresholdvalue.
SQL>select*frombookswherecontains(info,'propertyACCUMharvests')>0
SQL>select*frombookswherecatsearch(info,'propertyACCUMharvests',null)>0
InsteadofORyoucanuseacomma(,).
SQL>select*frombookswherecontains(info,'property,harvests')>0
SQL>select*frombookswherecatsearch(info,'property,harvests',null)>0
InthefollowingqueriestheMINUSoperatorsubtractsthescoreofthesecondterm'ssearchfromthe
scoreofthefirstterm'ssearch.
SQL>select*frombookswherecontains(info,'propertyMINUSharvests')>0
SQL>select*frombookswherecatsearch(info,'propertyNOTharvests',null)>0
InsteadofMINUSyoucanuseandinsteadofNOTyoucanuse~.
SQL>select*frombookswherecontains(info,'propertyharvests')>0
SQL>select*frombookswherecatsearch(info,'property~harvests',null)>0
SEARCHINGFORANEXACTMATCHOFAPHRASE
Thefollowingquerieswillsearchforthephrase.
Ifthesearchphraseincludesareservedwordwithinoracletext,theyoumustusecurlybraces({})toenclose
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

78 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

text.
SQL>select*frombookswherecontains(info,'transactions{and}finances')>0
SQL>select*frombookswherecatsearch(info,'transactions{and}finances',null)>0
Youcanenclosetheentirephrasewithincurlybraces,inwhichcaseanyreservedwordswithinthephrasewill
betreatedaspartofthesearchcriteria.

SQL>select*frombookswherecontains(info,'{transactionsandfinances}')>0
SQL>select*frombookswherecatsearch(info,'{transactionsandfinances}',null)>0
SEARCHINGFORWORDSTHATARENEAREACHOTHER
Thefollowingquerieswillsearchforthewordsthatareinbetweenthesearchterms.
SQL>select*frombookswherecontains(info,'workersNEARharvests')>0
InsteadofNEARyoucanuse.
SQL>select*frombookswherecontains(info,'workersharvests')>0
InCONTEXTindexqueries,youcanspecifythemaximumnumberofwordsbetweenthesearchterms.
SQL>select*frombookswherecontains(info,'NEAR((workers,harvests),10)'>0
USINGWILDCARDSDURINGSEARCHES
Youcanusewildcardstoexpandthelistofvalidsearchtermsusedduringyourquery.
Justasinregulartextstringwildcardprocessing,twowildcardsareavailable.
%percentsignmultiplecharacterwildcard_underscoresinglecharacterwildcard
SQL>select*frombookswherecontains(info,'worker%')>0
SQL>select*frombookswherecontains(info,'work___')>0
SEARCHINGFORWORDSTHATSHARETHESAMESTEM
Ratherthanusingwildcards,youcanusestemexpansioncapabilitiestoexpandthelistoftextstrings.
Giventhe'stem'ofaword,oraclewillexpandthelistofwordstosearchfortoincludeallwordshavingthe
samestem.
Sampleexpansionsareshowhere.Playplaysplayingplayedplayful
SQL>select*frombookswherecontains(info,'$manage')>0
SEARCHINGFORFUZZYMATCHES
1. Afuzzymatchexpandsthespecifiedsearchtermtoincludewordsthatarespelledsimilarlybutthatdonot
necessarilyhavethesamewordstem.Fuzzymatchesaremosthelpfulwhenthetextcontains
misspellings.
2. Themisspellingscanbeeitherinthesearchedtextorinthesearchstringspecifiedbytheuserduringthe
query.
3. Thefollowingquerieswillnotreturnanythingbecauseitssearchdoesnotcontaintheword'hardest'.
SQL>select*frombookswherecontains(info,'hardest')>0

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

79/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

1. Itdoes,however,containstheword'harvest'.
2. Afuzzymatchwillreturnthebookscontainingtheword'harvest'eventhough'harvest'hasadifferent
wordstemthantthewordusedasthesearchterm.
3. Touseafuzzymatch,precedethesearchtermwithaquestionmark,withnospacebetweenthequestion
markandthebeginningofthesearchterm.
SQL>select*frombookswherecontains(info,'?hardest')>0
SEARCHINGFORWORDSTHATSOUNDLIKEOTHERWORDS
1. SOUNDEX,expandssearchtermsbasedonhowthewordsounds.
2. TheSOUNDEXexpansionmethodusesthesametextmatchinglogicavailableviatheSOUNDEX
functioninSQL.
3. TousetheSOUNDEXoption,youmustprecedethesearchtermwithanexclamationmark(!).
SQL>select*frombookswherecontains(info,'!grate')>0
INDEXSYNCHRONIZATION
WhenusingCONTEXTindexes,youneedtomanagethetextindexcontents
thetextindexesarenotupdatedwhenthebasetableisupdated.
Whenthetablewasupdated,itstextindexisoutofsyncwiththebasetable.
Tosyncoftheindex,executetheSYNC_INDEXprocedureoftheCTX_DDLpackage.
SQL>execCTX_DDL.SYNC_INDEX('book_index')
INDEXSETS
Historically,problemswithqueriesoftextindexeshaveoccurredwhenothercriteriaareusedalongside
textsearchesaspartofthewhereclause.
Toimprovethemixedquerycapability,oraclefeaturesindexsets.
Theindexeswithintheindexsetmaybestructuredrelationalcolumnsorontextcolumns.
Tocreateanindexset,usetheCTX_DDLpackagetocreatetheindexsetandaddindexestoit.
Whenyoucreateatextindex,youcanthenspecifytheindexsetitbelongsto.
SQL>execCTX_DDL.CREATE_INDEX_SET('books_index_set')Theaddnontextindexes.
SQL>execCTX_DDL.ADD_INDEX('books_index_set','title_index')NowcreateaCTXCATtextindex.
Specifyctxsys.ctxcatastheindextype,andlisttheindexsetintheparametersclause.
SQL>createindexbook_indexonbooks(info)indextypeisctxsys.ctxcatparameters('indexset
books_index_set')
INDEXORGANIZEDTABLE
1. Anindexorganizedtablekeepsitsdatasortedaccordingtotheprimarykeycolumnvaluesforthetable.
2. Indexorganizedtablesstoretheirdataasiftheentiretablewasstoredinanindex.
3. Anindexorganizedtableallowsyoutostoretheentiretable'sdatainanindex.
Ex:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

8 0/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>createtablestudent(snonumber(2),snamevarchar(10),smarksnumber(3)constraintpk
primarykey(sno)organizationindex
PARTITIONINDEX
Similartopartitioningtables,oracleallowsyoutopartitionindexestoo.
Liketablepartitions,indexpartitionscouldbeindifferenttablespaces.
LOCALINDEXES
Localkeywordtellsoracletocreateaseparteindexforeachpartition.
Inthelocalprefixedindexthepartitionkeyisspecifiedontheleftprefix.Whentheunderlyingtableis
partitionedbaeson,saytwocolumnsthentheindexcanbeprefixedonthefirstcolumnspecified.
Localprefixedindexescanbeuniqueornonunique.
Localindexesmaybeeasiertomanagethanglobalindexes.
Ex:
SQL>createindexstud_indexonstudent(sno)local
GLOBALINDEXES
Aglobalindexmaycontainvaluesfrommultiplepartitions.
Anindexisglobalprefixedifitispartitionedontheleftprefixoftheindexcolumns.
Theglobalclauseallowsyoutocreateanonpartitionedindex.
Globalindexesmayperformuniquenesschecksfasterthanlocal(partitioned)indexes.
Youcannotcreateglobalindexesforhashpartitionsorsubpartitions.
Ex:
SQL>createindexstud_indexonstudent(sno)global
Similartotablepartitions,itispossibletomovethemfromonedevicetoanother.
Butunliketablepartitions,movementofindexpartitionsrequiresindividualreconstructionoftheindexor
eachpartition(onlyinthecaseofglobalindex).

Ex:
SQL>alterindexstud_indrebuildpartitionp2
Indexpartitionscannotbedroppedmanually.
Theyaredroppedimplicitlywhenthedatatheyrefertoisdroppedfromthepartitionedtable.
MONITORINGUSEOFINDEXES
Onceyouturnedonthemonitoringtheuseofindexes,thenwecancheckwhetherthetableishittingthe
indexornot.
Tomonitortheuseofindexusethefollwingsyntax.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

8 1/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Syntax:
alterindexindex_namemonitoringusage
thencheckforthedetailsinV$OBJECT_USAGEview.
Ifyouwanttostopmonitoringusethefollowing.
Syntax:
alterindexindex_namenomonitoringusage
DATAMODEL
ALL_INDEXES
DBA_INDEXES
USER_INDEXES
ALL_INDCOLUMNS
DBAIND_COLUMNS
USER_IND_COLUMNS
ALL_PART_INDEXES
DBA_PART_INDEXES
USER_PART_INDEXES
V$OBJECT_USAGE
SQL*PLUSCOMMNANDS
Thesecommandsdoesnotrequirestatementterminatorandapplicabletothesessions,thosewillbe
automaticallyclearedwhensessionwasclosed.
BREAK
Thiswillbeusedtobreakupthedatadependingonthegrouping.
Syntax:
Breakorbre[on<column_name>onreport]
COMPUTE
Thiswillbeusedtoperformgroupfunctionsonthedata.
Syntax:
Computeorcomp[group_functionofcolumn_nameonbreaking_column_nameorreport]
TTITLE
Thiswillgivethetoptitleforyourreport.Youcanonoroffthettitle.
Syntax:
Ttitleorttit[left|center|right]title_nameskipnother_characters
Ttitleorttit[onoroff]
BTITLE
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

8 2/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Thiswillgivethebottomtitleforyourreport.Youcanonoroffthebtitle.
Syntax:
Btitleorbtit[left|center|right]title_nameskipnother_characters
Btitleorbtit[onoroff]
Ex:
SQL>breondeptnoskip1onreport
SQL>compsumofsalondeptno
SQL>compsumofsalonreport
SQL>ttitlecenter'EMPLOYEEDETAILS'skip1center''
SQL>btitlecenter'**THANKQ**'
SQL>select*fromemporderbydeptnoOutput:

EMPLOYEE DETAILS
----------------------EMPNO
ENAME
JOB
MGR
------ ------- -------- ------7782
CLARK MANAGER
7839
7839
KING PRESIDENT
7934
MILLER CLERK
7782

HIREDATE
SAL
COMM DEPTNO
--------- -------- ------ ---------09-JUN-81
2450
10
17-NOV-81
5000
23-JAN-82
1300
--------- **********
8750
sum

7369
7876
7902
7788
7566

SMITH
ADAMS
FORD
SCOTT
JONES

7902
7788
7566
7566
7839

17-DEC-80
23-MAY-87
03-DEC-81
19-APR-87
02-APR-81

7499
7698
7654
7900
7844
7521

ALLEN SALESMAN
BLAKE MANAGER
MARTIN SALESMAN
JAMES CLERK
TURNER SALESMAN
WARD SALESMAN

7698
7839
7698
7698
7698
7698

20-FEB-81
01-MAY-81
28-SEP-81
03-DEC-81
08-SEP-81
22-FEB-81

CLERK
CLERK
ANALYST
ANALYST
MANAGER

sum

800
20
1100
3000
3000
2975
---------- **********
10875
sum
1600
300 30
2850
1250
1400
950
1500
0
1250
500
---------- **********
9400
sum
---------29025

** THANKQ **

CLEAR
Thiswillcleartheexistingbuffersorbreakorcomputationsorcolumnsformatting.
Syntax:
Clearorclebuffer|bre|comp|col
Ex:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

8 3 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>clearbuffer
Buffercleared
SQL>clearbre
Breakscleared
SQL>clearcomp
Computescleared
SQL>clearcol
Columnscleared
CHANGE
ThiswillbeusedtoreplaceanystringsinSQLstatements.
Syntax:
Changeorc/old_string/new_string
Iftheold_stringrepeatsmanytimesthennew_stringreplacesthefirststringonly.
Ex:
SQL>select*fromdet
select*fromdet
*
ERRORatline1:
ORA00942:tableorviewdoesnotexist
SQL>c/det/dept
1*select*fromdept
SQL>/
DEPTNO
DNAME
LOC
---------- ------------ ----------10
ACCOUNTING NEW YORK
20
RESEARCH
ALLAS
30
SALES
CHICAGO
40
OPERATIONS BOSTON

COLUMN
Thiswillbeusedtoincreaseordecreasethewidthofthetablecolumns.
Syntax:
Columnorcol<column_name>format<num_format|text_format>
Ex:
SQL>coldeptnoformat999
SQL>coldnameformata10
SAVE
ThiswillbeusedtosaveyourcurrentSQLstatementasSQLScriptfile.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

8 4/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Syntax:
Saveorsav<file_name>.[extension]replaceorrep
Ifyouwanttosavethefilenamewithexistingfilenametheyouhavetousereplaceoption.Bydefaultitwill
takesqlastheextension.
Ex:
SQL>savess
Createdfiless.sql
SQL>savessreplace
Wrotefiless.sql
EXECUTE
Thiswillbeusedtoexecutestoredsubprogramsorpackagedsubprograms.
Syntax:
Executeorexec<subprogram_name>
Ex:
SQL>execsample_proc
SPOOL
Thiswillrecordthedatawhenyouspoolon,uptowhenyousayspooloff.Bydefaultitwillgivelstas
extension.
Syntax:
Spoolon|off|out|<file_name>.[Extension]
Ex:
SQL>spoolon
SQL>select*fromdept
DEPTNO DNAME
------- -----------10
ACCOUNTING
20
RESEARCH
30
SALES
40
OPERATIONS

LOC
---------NEW YORK
DALLAS
CHICAGO
BOSTON

SQL>spooloff
SQL>edon.lst
SQL>select*fromdept
DEPTNO DNAME
------ -----------10
ACCOUNTING
20
RESEARCH

LOC
---------NEW YORK
DALLAS

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

8 5 /18 2

7/4/2016

30
40

plsqlH om e Oracle , PL/SQL M at erial

SALES
OPERATIONS

CHICAGO
BOSTON

SQL>spooloff
LIST
ThiswillgivethecurrentSQLstatement.
Syntax:
Listorli[start_line_number][end_line_number]
Ex:
SQL>select
2*
3from
4dept
SQL>list
1select
2*
3from
4*dept
SQL>list1
1*select
SQL>list3
3*from
SQL>list13
1select
2*
3*from
INPUT
ThiswillinsertthenewlinetothecurrentSQLstatement.
Syntax:
Inputorin<string>
Ex:
SQL>select*
SQL>list
1*select*
SQL>inputfromdept
SQL>list
1select*
2*fromdept
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

8 6/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

APPEND
ThiswilladdsanewstringtotheexistingstringintheSQLstatementwithoutanyspace.
Syntax:
Appendorapp<string>
Ex:
SQL>select*
SQL>list
1*select*
SQL>appendfromdept
1*select*fromdept
SQL>list
1*select*fromdept
DELETE
ThiswilldeletethecurrentSQLstatementlines.
Syntax:
Deleteordel<start_line_number>[<end_line_number>]
Ex:
SQL>select
2*
3from
4dept
5where
6deptno
7>10
SQL>list
1select
2*
3from
4dept
5where
6deptno
7*>10
SQL>del1
SQL>list
1*
2from
3dept
4where
5deptno
6*>10
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

8 7/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>del2
SQL>list
1*
2dept
3where
4deptno
5*>10
SQL>del24
SQL>list
1*
2*>10
SQL>del
SQL>list
1*
VARIABLE
Thiswillbeusedtodeclareavariable.
Syntax:
Variableorvar<variable_name><variable_type>
Ex:
SQL>vardept_namevarchar(15)
SQL>selectdnameintodept_namefromdeptwheredeptno=10
PRINT
ThiswillbeusedtoprinttheoutputofthevariablesthatwillbedeclaredatSQLlevel.
Syntax:
Print<variable_name>
Ex:
SQL>printdept_name
DEPT_NAME
-------------ACCOUNTING

START
ThiswillbeusedtoexecuteSQLscripts.
Syntax:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

8 8 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

start<filename_name>.sql
Ex:
SQL>startss.sql
SQL>@ss.sqlthiswillexecutesqlscriptfilesonly.
HOST
ThiswillbeusedtointeractwiththeOSlevelfromSQL.
Syntax:
Host[operation]
Ex:
SQL>host
SQL>hostdir
SHOW
Usingthis,youcanseeseveralcommandsthatusethesetcommandandstatus.
Syntax:
Showall|<set_command>
Ex:
SQL>showall
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>showverify
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

8 9/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

verifyOFF
RUN
Thiswillrunsthecommandinthebuffer.
Syntax:
Run|/
Ex:
SQL>run
SQL>/
STORE
Thiswillsaveallthesetcommandstatusesinafile.
Syntax:
Storeset<filename>.[extension][create]|[replace]|[append]
Ex:
SQL>storesetmy_settings.scmdCreatedfilemy_settings.scmd
SQL>storesetmy_settings.cmdreplaceWrotefilemy_settings.cmd
SQL>storesetmy_settings.cmdappendAppendedfiletomy_settings.cmd
FOLD_AFTER
Thiswillfoldthecolumnsoneaftertheother.
Syntax:
Column<column_name>fold_after[no_of_lines]
Ex:
SQL>coldeptnofold_after1
SQL>coldnamefold_after1
SQL>collocfold_after1
SQL>setheadingoff
SQL>select*fromdept
10
ACCOUNTING
NEW YORK
20
RESEARCH
DALLAS
30
SALES
CHICAGO
40
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

90/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

OPERATIONS
BOSTON

FOLD_BEFORE
Thiswillfoldthecolumnsonebeforetheother.
Syntax:
Column<column_name>fold_before[no_of_lines]
DFINE
Thiswillgivethelistofallthevariablescurrentlydefined.
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)

SETCOMMANDS
Thesecommandsdoesnotrequirestatementterminatorandapplicabletothesessions,thosewillbe
automaticallyclearedwhensessionwasclosed.
LINESIZE
Thiswillbeusedtosetthelinesize.
Defaultlinesizeis80.
Syntax:
Setlinesize<value>
Ex:
SQL>setlinesize100
PAGESIZE
Thiswillbeusedtosetthepagesize.
Defaultpagesizeis14.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

91/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Syntax:
Setpagesize<value>
Ex:
SQL>setpagesize30
DESCRIBE
Thiswillbeusedtoseetheobject'sstructure.
Syntax:
Describeordesc<object_name>
Ex:
SQL>descdept
Name
--------DEPTNO
DNAME
LOC

Null?
------------NOT NULL

Type
-----------NUMBER(2)
VARCHAR2(14)
VARCHAR2(13)

PAUSE
Whenthedisplayeddatacontainshundredsorthousandsoflines,whenyouselectitthenitwill
automaticallyscrollsanddisplaysthelastpagedata.
Topreventthisyoucanusethispauseoption.
Byusingthisitwilldisplaythedatacorrespoindingtothepagesizewithabreakwhichwillcontinueby
hittingthereturnkey.
Bydefaultthiswillbeoff.
Syntax:
Setpauseon|off
Ex:
SQL>setpauseon
FEEDBACK
Thiswillgivetheinformationregardinghowmanyrowsyouselectedtheobject.
Bydefaultthefeedbackmessagewillbedisplayed,onlywhentheobjectcontainsmorethan5rows.
Syntax:
Setfeedback<value>
Ex:
SQL>setfeedback4
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

92/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>select*fromdept
DEPTNO
DNAME
LOC
-------- -------------- ------------10
ACCOUNTING
NEW YORK
20
RESEARCH
DALLAS
30
SALES
CHICAGO
40
OPERATIONS
BOSTON
4 rows selected.

HEADING
Ifyouwanttodisplaydatawithoutheadings,thenyoucanachievewiththis.
Bydefaultheadingison.
Syntax:
Setheadingon|off
Ex:
SQL>setheadingoff
SQL>select*fromdept
10
20
30
40

ACCOUNTING
RESEARCH
SALES
OPERATIONS

NEW YORK
DALLAS
CHICAGO
BOSTON

SERVEROUTPUT
ThiswillbeusedtodisplaytheoutputofthePL/SQLprograms.
Bydefaultthiswillbeoff.
Syntax:
Setserveroutputon|off
Ex:
SQL>setserveroutputon
TIME
Thiswillbeusedtodisplaythetime.
Bydefaultthiswillbeoff.
Syntax:
Settimeon|off
Ex:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

93 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>settimeon
19:56:33 SQL>

TIMING
ThiswillgivethetimetakentoexecutethecurrentSQLstatement.
Bydefaultthiswillbeoff.
Syntax:
Settimingon|off
Ex:
SQL>settimingon
SQL>select*fromdept
DEPTNO
DNAME
LOC
-------- ---------- ------------10 ACCOUNTING
NEW YORK
20 RESEARCH
DALLAS
30 SALES
CHICAGO
40 OPERATIONS
BOSTON
Elapsed: 00:00:00.06

SQLPROMPT
ThiswillbeusedtochangetheSQLprompt.
Syntax:
Setsqlprompt<prompt>
Ex:
SQL>setsqlprompt'ORACLE>'
ORACLE>

SQLCASE
ThiswillbeusedtochangethecaseoftheSQLstatements.
Bydefaultthecaseismixed.
Syntax:
Setsqlcaseupper|mixed|lower
Ex:

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

94/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SQL>setsqlcaseupper
SQLTERMINATOR
ThiswillbeusedtochangetheterminatoroftheSQLstatements.
Bydefaulttheterminatoris.
Syntax:
Setsqlterminator<termination_character>
Ex:
SQL>setsqlterminator:
SQL>select*fromdept:
DEFINE
Bydefaultifthe&characterfindsthenitwilltreatasbindvariableandaskfortheinput.
Supposeyourwanttotreatitasanormalcharacterwhileinsertingdata,thenyoucanpreventthisby
usingthedefineoption.
Bydefaultthiswillbeon
Syntax:
Setdefineon|off
Ex:
SQL>insertintodeptvalues(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>setdefineoff
SQL>insertintodeptvalues(50,'R&D','HYD')hereitwon'taskforvalue
NEWPAGE
Thiswillshowshowmanyblanklineswillbeleftbeforethereport.
Bydefaultitwillleaveoneblankline.
Syntax:
Setnewpage<value>
Ex:
SQL>setnewpage10
Thezerovaluefornewpagedoesnotproducezeroblanklinesinsteaditswitchestoaspecialproperty
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

95 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

whichproducesatopofformcharacter(hex13)justbeforethedateoneachpage.
Mostmodernprintersrespondtothisbymovingimmediatelytothetopofthenextpage,wherethepriting
ofthereportwillbegin.
HEADSEP
Thisallowyoutoindicatewhereyouwanttobreakapagetitleoracolumnheadingthatrunslongerthan
oneline.
Thedefaultheadingseparatorisverticalbar(|).
Syntax:
Setheadsep<separation_char>
Ex:
SQL>select*fromdept
DEPTNO
DNAME
------- ----------10 ACCOUNTING
20 RESEARCH
30 SALES
40 OPERATIONS

LOC
------------NEW YORK
DALLAS
CHICAGO
BOSTON

SQL>setheadsetp!
SQL>coldnameheading'DEPARTMENT!NAME'
SQL>/
DEPARTMENT
DEPTNO
NAME
---------- -------------10
ACCOUNTING
20
RESEARCH
30
SALES
40
OPERATIONS

LOC
---------NEW YORK
DALLAS
CHICAGO
BOSTON

ECHO
Whenusingabindvariable,theSQLstatementismaintainedbyecho.
Bydefaultthisisoff.
Syntax:
Setechoon|off
VERIFY
Whenusingabindvariable,theoldandnewstatementswillbemaintainedbyverify.
Bydefaultthisison.

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

96/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Syntax:
Setverifyon|off
Ex:
SQL>select*fromdeptwheredeptno=&dno
Enter value for dno: 10
old 1: select * from dept where deptno = &dno
new 1: select * from dept where deptno = 10
DEPTNO
DNAME
-------- -----------10
ACCOUNTING

LOC
----------NEW YORK

SQL>setverifyoff
SQL>select*fromdeptwheredeptno=&dno
Enter value for dno: 20
DEPTNO
DNAME
LOC
-------- ---------- ----------20
RESEARCH
DALLAS

PNO
Thiswillgivedisplaysthepagenumbers.
Bydefaultthevaluewouldbezero.
Ex:
SQL>colhiredatenew_valuextodaynoprintformata1trunc
SQL>ttitleleftxtodayright'page'sql.pno
SQL>select*fromempwheredeptno=10
09-JUN-81
EMPNO ENAME
JOB
MGR
SAL COMM
------ -------- ---------- ------- ----- ----7782 CLARK
MANAGER
7839
2450
7839 KING
PRESIDENT
5000
7934 MILLER
CLERK
7782
1300

page 1
DEPTNO
-------10
10
10

IntheabovenoprinttellsSQLPLUSnottodisplaythiscolumnwhenitprintstheresultsoftheSQL
statement.
DatesthathavebeenreformattedbyTO_CHARgetadefaultwidthofabout100characters.Bychanging
theformattoa1trunc,youminimizethiseffect.
NEW_VALUEinsertscontentsofthecolumnretrievedbytheSQLstatementintoavariablecalled
xtoday.
SPECIALFILES
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

97/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

LOGIN.sql
IfyouwouldlikeSQLPLUStodefineyourownenvironmentalsettings,putalltherequiredcommandsin
afilenamedlogin.sql.
ThisisaspecialfilenamethatSQLPLUSalwayslooksforwheneveritstartsup.
Ifitfindslogin.sql,itexecutesanycommandsinitasifyouhadenteredthenbyhand.
Youcanputanycommandinlogin.sqlthatyoucanuseinSQLPLUS,includingSQLPLUScommands
andSQLstatements.
AlltothemexecutedbeforeSQLPLUSgivesyoutheSQL>prompt.
GLOGIN.sql
ThisisusedinthesamewaysasLOGIN.sqlbuttoestablishdefaultSQLPLUSsettingsforallusersofa
database.
IMPQUERIES
1. Tofindthenthrowofatable
SQL>Select*fromempwhererowid=(selectmax(rowid)fromempwhererownum<=4)Or
SQL>Select*fromempwhererownum<=4minusselect*fromempwhererownum<=3
2. Tofindduplicaterows
SQL>Select*fromempwhererowidin(selectmax(rowid)fromempgroupbyempno,ename,mgr,job,
hiredate,comm,deptno,sal)Or
SQL>Selectempno,ename,sal,job,hiredate,comm,count(*)fromempgroupby
empno,ename,sal,job,hiredate,commhavingcount(*)>=1
3. Todeleteduplicaterows
SQL>Deleteempwhererowidin(selectmax(rowid)fromempgroupby
empno,ename,mgr,job,hiredate,sal,comm,deptno)
4. Tofindthecountofduplicaterows
SQL>Selectename,count(*)fromempgroupbyenamehavingcount(*)>=1
5. Howtodisplayalternativerowsinatable?
SQL>select*fromempwhere(rowid,0)in(selectrowid,mod(rownum,2)fromemp)
6. Gettingemployeedetailsofeachdepartmentwhoisdrawingmaximumsal?
SQL>select*fromempwhere(deptno,sal)in(selectdeptno,max(sal)fromempgroupbydeptno)
7. Howtogetnumberofemployeesineachdepartment,inwhichdepartmentishavingmorethan
2500employees?
SQL>Selectdeptno,count(*)fromempgroupbydeptnohavingcount(*)>2500
8. Toresetthetimetothebeginningoftheday
SQL>Selectto_char(trunc(sysdate),'ddmonyyyyhh:mi:ssam')fromdual
9. Tofindnthmaximumsal
SQL>Select*fromempwheresalin(selectmax(sal)from(select*fromemporderbysal)where
rownum<=5)
INTRODUCTION
CHARACTERSTICS
Highlystructured,readableandaccessiblelanguage.
StandardandProtablelanguage.
Embeddedlanguage.
Improvedexecutionauthority.
10gFEATURES
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

98 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Optimizedcompiler
Tochangetheoptimizersettingsfortheentiredatabase,setthedatabaseparameter
PLSQL_OPTIMIZE_LEVEL.Validsettingsareasfollows
0Nooptimization
1Moderateoptimization
2Aggressiveoptimization
Thesesettingsarealsomodifiableforthecurrentsession.
SQL>altersessionsetplsql_optimze_level=2
Oracleretainsoptimizersettingsonamodulebymodulebasis.Whenyourecompileaparticularmodule
withnondefaultsettings,thesettingswillstickallowingyoutorecompilelateronusingREUSE
SETTINGS.
SQL>Alterprocedureproccompileplsql_optimize_level=1
SQL>Alterprocedureproccompilereusesettings
Compiletimewarnings.
Startingwithoracledatabase10grelease1youcanenableadditionalcompiletimewarningstohelpmake
yourprogramsmorerobust.Thecompilercandetectpotentialruntimeproblemswithyourcode,suchas
identifyinglinesofcodethatwillneverberun.Thisprocess,alsoknownaslintchecking.
Toenablethesewarningsfortheentiredatabase,setthedatabaseparameterPLSQL_WARNINGS.These
settingsarealsomodifiableforthecurrentsession.
SQL>altersessionsetplsql_warnings='enable:all'Theabovecanbeachievedusingthebuiltin
packageDBMS_WARNING.
Conditionalcompilation.
Conditionalcompilationallowsthecompilertoallowtocompileselectedpartsofaprogrambasedon
conditionsyouprovidewiththe$IFdirective.
SupportfornonsequentialcollectionsinFORALL.
Improveddatatypesupport.
Backtraceanexceptiontoitslinenumber.
Whenhandlinganerror,howcanyoufindthelinenumberonwhichtheerrorwasoriginallyraised?
Inearlierrelease,theonlywaytodothiswasallowyouexceptiontogounhandledandthenviewthefull
errortracestack.
NowyoucancallDBMS_UTILITY.FORMAT_ERROR_BACKTRACEfunctiontoobtainthatstack
andmanipulateitprogrammaticallywithinyourprogram.
Setoperatorsfornestedtables.
builtinfunctions.
REGEXP_LIKE
REGEXP_INSTR
REGEXP_SUBSTR
REGEXP_REPLACE
Programmerdefinedquotingmechanism.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

99/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Startingwithoracledatabase10grelease1,youcandefineyourownquotingmechanismforstringliterals
inbothSQLandPL/SQL.
Usethecharactersq'(qfollowedbyasinglequote)tonotetheprogrammerdefineddeliemeterforyou
stringliteral.
Ex:
DECLARE
v varchar(10) := 'computer';
BEGIN
dbms_output.put_line(q'*v = *' || v);
dbms_output.put_line(q'$v = $' || v);
END;
Output:
v = computer
v = computer

Manynewbuiltinpackages.
DBMS_SCHEDULER
RepresentsamajorupdatetoDBMS_JOB.DBMS_SCHEDULERprovidesmuchimprovedfunctionality
forschedulingandexecutingjobsdefinedviastoredprocedures.
DBMS_CRYPTO
Offerstheabilitytoencryptanddecryptcommonoracledatatype,includingRAWs,BLOBs,andCLOBs.
Italsoprovidesglobalizationsupportforencryptingdataacrossdifferentcharactersets.
DBMS_MONITOR
ProvidesanAPItocontroladditionaltracingandstatisticsgatheringofsessions.
DBMS_WARNING
ProvidesanAPIintothePL/SQLcompilerwarningsmodule,allowingyoutoreadandchangesettings
thatcontrolwhichwarningsaresuppressed,displayed,ortreatedaserrors.
STANDARDPACKAGE
Oraclehasdefinedinthisspecialpackage.Oracledefinesquiteafewidentifiersinthispackage,including
builtinexceptions,functionsandsubtypes.Youcanreferencethebuiltinformbyprefixingitwith
STANDARD.
ThebasicunitinanyPL/SQLprogramisblock.AllPL/SQLprogramsarecomposedofblockswhichcan
occursequentiallyornested.
BLOCKSTRUCTURE
Declare
-- declarative section
Begin
-- executable section
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

100/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Exception
-- exception section
End;

Intheabovedeclarativeandexceptionasectionsareoptional.
BLOCKTYPES
Anonymousblocks
Namedblocks
Labeledblocks
Subprograms
Triggers
ANONYMOUSBLOCKS
Anonymousblocksimpliesbasicblockstructure.
Ex:
BEGIN
Dbms_output.put_line('My first program'):
END;

LABELEDBLOCKS
Labeledblocksareanonymousblockswithalabelwhichgivesanametotheblock.
Ex:
<<my_bloock>>
BEGIN
Dbms_output.put_line('My first program'):
END;

SUBPROGRAMS
Subprogramsareproceduresandfunctions.Theycanbestoredinthedatabaseasstandaloneobjects,aspart
ofpackageorasmethodsofanobjecttype.
TRIGGERS
TriggersconsistsofaPL/SQLblockthatisassociatedwithaneventthatoccurinthedatabase.
NESTEDBLOCKS
Ablockcanbenestedwithintheexecutableorexceptionsectionofanouterblock.
IDENTIFIERS
IdentifiersareusedtonamePL/SQLobjects,suchasvariables,cursors,typesandsubprograms.Identifiers
consistsofaletter,optionallyfollowedbyanysequenceofcharacters,includingletters,numbers,dollarsigns,
underscores,andpoundsignsonly.Themaximumlengthforanidentifieris30characters.
QUOTEDIDENTIFIERS
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

101/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Ifyouwanttomakeanidentifiercasesensitive,includecharacterssuchasspacesoruseareservedword,you
canenclosetheidentifierindoublequotationmarks.
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

COMMENTS
Commentsimprovereadabilityandmakeyourprogrammoreunderstandable.Theyareignoredbythe
PL/SQLcompiler.Therearetwotypesofcommentsavailable.
Singlelinecomments
Multilinecomments
SINGLELINECOMMENTS
Asinglelinecommentcanstartanypointonalinewithtwodashesandcontinuesuntiltheendoftheline.
Ex:
BEGIN
Dbms_output.put_line('hello');
END;

-- sample program

MULTILINECOMMENTS
Multilinecommentsstartwiththe/*delimiterandendswith*/delimiter.
Ex:
BEGIN
Dbms_output.put_line('hello');
END;

/* sample program */

VARIABLEDECLERATIONS
Variablescanbedeclaredindeclarativesectionoftheblock
Ex:
DECLARE
a number;
b number := 5;
c number default 6;

CONSTANTDECLERATIONS
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

102/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Todeclareaconstant,youincludetheCONSTANTkeyword,andyoumustsupplyadefaultvalue.
Ex:
DECLARE
b constant number := 5;
c constant number default 6;

NOTNULLCLAUSE
Youcanalsospecifythatthevariablemustbenotnull.
Ex:
DECLARE
b constant number not null:= 5;
c number not null default 6;

ANCHOREDDECLERATIONS
PL/SQLofferstwokindsofachoring.
Scalaranchoring
Recordanchoring
SCALARANCHORING
Usethe%TYPEattributetodefineyourvariablebasedontable'scolumnofsomeotherPL/SQLscalar
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;

RECORDANCHORING
Usethe%ROWTYPEattributetodefineyourrecordstructurebasedonatable.
Ex:
DECLARE
V_dept dept%rowtype;

BENEFITSOFANCHOREDDECLARATIONS
Synchronizationwithdatabasecolumns.
Normalizationoflocalvariables.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

103 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

PROGRAMMERDEFINEDTYPES
WiththeSUBTYPEstatement,PL/SQLallowsyoutodefineyourownsubtypesoraliasesofpredefined
datatypes,sometimesreferredtoasabstractdatatypes.
Therearetwokindsofsubtypes.
Constrained
Unconstrained
CONSTRAINEDSUBTYPE
Asubtypethatrestrictsorconstrainsthevaluesnormallyallowdbythedatatypeitself.
Ex:
Subtypepositiveisbinary_integerrange1..2147483647
Intheabovedeclarationavariablethatisdeclaredaspositivecanstoreonlyingegergreaterthanzeroeven
thoughbinary_integerrangesfrom2147483647..+2147483647.
UNCONSTRAINEDSUBTYPE
Asubtypethatdoesnotrestrictthevaluesoftheoriginaldatatypeinvariablesdeclaredwiththesubtype.
Ex:
Subtypefloatisnumber
DATATYPECONVERSIONS
PL/SQLcanhandleconversionsbetweendifferentfamiliesamongthedatatypes.Conversioncanbedonein
twoways.
Explicitconversion
Implicitconversion
EXPLICITCONVERSION
Thiscanbedoneusingthebuiltinfunctionsavailable.
IMPLICITCONVERSION
PL/SQLwillautomaticallyconvertbetweendatatypefamilieswhenpossible.
Ex:
DECLARE
a varchar(10);
BEGIN
select deptno into a from dept where dname='ACCOUNTING';
END;

Intheabovevariableaischartypeanddeptnoisnumbertypeeventhough,oraclewillautomaticallyconverts
thenumericdataintochartypeassignstothevariable.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

104/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

PL/SQLcanautomaticallyconvertbetween
Charactersandnumbers
Charactersanddates
VARIABLESCOPEANDVISIBILITY
Thescopeofavariableistheportionoftheprograminwhichthevariablecanbeaccessed.ForPL/SQL
variables,thisisfromthevariabledeclarationuntiltheendoftheblock.Whenavariablegoesoutofscope,
thePL/SQLenginewillfreethememoryusedtostorethevariable.
Thevisibilityofavariableistheportionoftheprogramwherethevariablecanbeaccessedwithouthavingto
qualifythereference.Thevisibilityisalwayswithinthescope.Ifitisoutofscope,itisnotvisible.
Ex1:
DECLARE
a number;
BEGIN
--------

-- scope of a

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
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

105 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

END;
-----END;

PL/SQLCONTROLSTRUCTURES
PL/SQLhasavarietyofcontrolstructuresthatallowyoutocontrolthebehaviouroftheblockasitruns.
Thesestructuresincludeconditionalstatementsandloops.
Ifthenelse
Case
Casewithnoelse
Labeledcase
Searchedcase
Simpleloop
Whileloop
Forloop
GotoandLabels
IFTHENELSE
Syntax:
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

CASE
Syntax:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

106/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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

CASEWITHOUTELSE
Syntax:
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;

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

107/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Output:
Location is NEW YORK

LABELEDCASE
Syntax:
<<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

SEARCHEDCASE
Syntax:
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
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

108 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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

SIMPLELOOP
Syntax:
Loop
Sequence of statements;
Exit when <condition>;
End loop;

Inthesyntaxexitwhen<condition>isequivalentto
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

WHILELOOP
Syntax:
While <condition> loop
Sequence of statements;
End loop;

Ex:
DECLARE
i number := 1;
BEGIN
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

109/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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

FORLOOP
Syntax:
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

NULLSTATEMENT
Usuallywhenyouwriteastatementinaprogram,youwantittodosomething.
Therearecases,however,whenyouwanttotellPL/SQLtodoabsolutelynothing,andthatiswherethe
NULLcomes.
TheNULLstatementdeosnothingexceptpasscontroltothenextexecutablestatement.
YoucanuseNULLstatementinthefollowingsituations.
Improvingprogramreadability:Sometimes,itishelpfultoavoidanyambiguityinherentinanIF
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

110/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

statementthatdoesn'tcoverallpossiblecases.Forexample,whenyouwriteanIFstatement,youdonot
havetoincludeanELSEclause.
Nullifyingaraisedexception:Whenyoudon'twanttowriteanyspecialcodetohandleanexception,you
canusetheNULLstatementtomakesurethataraisedexceptionhaltsexecutionofthecurrentPL/SQL
blockbutdoesnotpropagateanyexceptionstoenclosingblocks.
Usingnullafteralabel:Insomecases,youcanpairNULLwithGOTOtoavoidhavingtoexecute
additionalstatements.Forexample,IuseaGOTOstatementtoquicklymovetotheendofmyprogramif
thestateofmydataindicatesthatnofurtherprocessingisrequired.BecauseIdonothavetodoanything
attheterminationoftheprogram,IplaceaNULLstatementafterthelabelbecauseatleastoneexecutable
statementisrequiredthere.EventhoughNULLdeosnothing,itisstillanexecutablestatement.
GOTOANDLABELS
Syntax:
Goto label;

WherelabelisalabeldefinedinthePL/SQLblock.Labelsareenclosedindoubleanglebrackets.Whena
gotostatementisevaluated,controlimmediatelypassestothestatementidentifiedbythelabel.
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

RESTRICTIONSONGOTO
Itisillegaltobranchintoaninnerblock,loop.
Atleastoneexecutablestatementmustfollow.
Itisillegaltobranchintoanifstatement.
Itisillegaltobranchfromoneifstatementtoanotherifstatement.
Itisillegaltobranchfromexceptionblocktothecurrentblock.
PRAGMAS
Pragmasarecompilerdirectives.TheyserveasinstructionstothePL/SQLcompiler.Thecompilerwillacton
thepragmaduringthecompilationoftheblock.
Syntax:
PRGAMA instruction_to_compiler.

PL/SQLoffersseveralpragmas:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

111/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

AUTONOMOUS_TRANSACTION
EXCEPTION_INIT
RESTRICT_REFERENCES
SERIALLY_REUSABLE
SUBPROGRAMS
PROCEDURES
Aprocedureisamodulethatperformsoneormoreactions.
Syntax:
Procedure [schema.]name [(parameter1 [,parameter2 ...])]
[authid definer | current_user] is
-- [declarations]
Begin
-- executable statements
[Exception
-- exception handlers]
End [name];

Intheaboveauthidclausedefineswhethertheprocedurewillexecuteundertheauthorityofthedefinerofthe
procedureorundertheauthorityofthecurrentuser.
FUNCTIONS
Afunctionisamodulethatreturnsavalue.
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];

Intheaboveauthidclausedefineswhethertheprocedurewillexecuteundertheauthorityofthedefinerofthe
procedureorundertheauthorityofthecurrentuser.
Deterministicclausedefines,anoptimizationhintthatletsthesystemuseasavedcopyofthefunction'sreturn
result,ifavailable.Thequetyoptimizercanchoosewhethertousethesavedcopyorrecallthefunction.
Parallel_enableclausedefines,anoptimizationhintthatenablesthefunctiontobeexecutedinparallelwhen
calledfromwithinSELECTstatement.
PARAMETERMODES
In(Default)
Out
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

112/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Inout
IN
Inparameterwillactaspl/sqlconstant.
OUT
Outparameterwillactasunintializedvariable.
Youcannotprovideadefaultvaluetoanoutparameter.
Anyassignmentsmadetooutparameterarerolledbackwhenanexceptionisraisedintheprogram.
Anactualparametercorrespondingtoanoutformalparametermustbeavariable.
INOUT
Inoutparameterwillactasinitializedvariable.
Anactualparametercorrespondingtoaninoutformalparametermustbeavariable.
DEFAULTPARAMETERS
DefaultParameterswillnotallowinthebeginningandmiddle.
OutandInOutparameterscannothavedefaultvalues.
Ex:
procedurep(ainnumberdefault5,binnumberdefault6,cinnumberdefault7)valid
procedurep(ainnumber,binnumberdefault6,cinnumberdefault7)valild
procedurep(ainnumber,binnumber,cinnumberdefault7)valild
procedurep(ainnumber,binnumberdefault6,cinnumber)invalild
procedurep(ainnumberdefault5,binnumberdefault6,cinnumber)invalild
procedurep(ainnumberdefault5,binnumber,cinnumber)invalild
NOTATIONS
Notationsareoftwotypes.
Positionalnotation
Namenotation
Wecancombinepositionalandnamenotationbutpositionalnotationcannotbefollowedbythename
notation.
Ex:
Supposewehaveaprocedureproc(anumber,bnumber,cnumber)andwehaveoneanonymousblockwhich
containsv1,v2,andv3
SQL>execproc(v1,v2,v3)Positionalnotation
SQL>execproc(a=>v1,b=>v2,c=>v3)Namednotation
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

113 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

FORMALANDACTUALPARAMETERS
Parameteswhichareincallingsubprogramareactualparameters.
Parameteswhichareincalledsubprogramareformalparameters.
Ifanysubprogramwascalled,oncethecallwascompletedthenthevaluesofformalparametersare
copiedtotheactualparameters.
Ex1:
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=4b= 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;
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

114/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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=1b= c=3
Before assignement Result = 3
After assignment
a=1b=5c=7
After call completed
v1 = 1 v2 = 5 v3 = 7
Result = 35

RESTRICTIONSONFORMALPARAMETERS
Bydeclaringwithspecifiedsizeinactualparameters.
Bydeclaringformalparameterswith%typespecifier.
USINGNOCOPY
Nocopyisahint,notacommand.Thismeansthatthecompilermightsilentlydecidethatitcan'tfulfill
yourrequestforanocopyparameter.
Thecopyingfromformaltoactualcanberestrictedbyissuingnocopyqualifier.
Topasstheoutandinoutparametersbyreferenceusenocopyqualifier.
Ex:
CREATE OR REPLACE PROCEDURE PROC(a in out nocopy number) IS
BEGIN
---END PROC;

CALLANDEXEC
CallisaSQLstatement,whichcanbeusedtoexecutesubprogramslikeexec.Syntax:Call
subprogram_name([argument_list])[intohost_variable]
Theparanthesesarealwaysrequired,evenifthesubprogramtakesnoarguments.
Wecannotusecallwithoutandinoutparameters.
CallisaSQLstatement,itisnotvalidinsideaPL/SQLblock
TheINTOclauseisusedfortheoutputvariablesoffunctionsonly.
Wecannotuse'exec'withoutorinoutparameters.
ExecisnotvalidinsideaPL/SQLblock
Ex1:
CREATE OR REPLACE PROC IS
BEGIN
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

115 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

dbms_output.put_line('hello world');
END PROC;
Output:
SQL> call proc();
hello world

Ex2:
CREATE OR REPLACE PROC(a in number,b in number) IS
BEGIN
dbms_output.put_line('a = ' || a || ' b = ' || b);
END PROC;
Output:
SQL> call proc(5,6);
a=5b=6

Ex3:
CREATE OR REPLACE FUNCTION FUN RETURN VARCHAR IS
BEGIN
return 'hello world';
END FUN;
Output:
SQL> variable v varchar(20)
SQL> call fun() into :v;
SQL> print v
hello world

CALLBYREFERENCEANDCALLBYVALUE
Inparametersbydefaultcallbyreferencewhereasoutandinoutcallbyvalue.
Whenparameterpassedbyreference,apointertotheactualparameterispassedtothecorresponding
formalparameter.
Whenparameterpassedbyvalueitcopiesthevalueoftheactualparametertotheformalparameter.
Callbyreferenceisfasterthanthecallbyvaluebecauseitavoidsthecopying.
SUBPROGRAMSOVERLOADING
Possiblewithdifferentnumberofparameters.
Possiblewithdifferenttypesofdata.
Possiblewithsametypewithobjects.
Cannotbepossiblewithdifferenttypesofmodes.
Wecanoverloadlocalsubprogramsalso.
Ex:
SQL>createorreplacetypet1asobject(anumber)/
SQL>createorreplacetypet1asobject(anumber)/
DECLARE
i t1 := t1(5);
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

116/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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

BENEFITSOFOVERLOADING
Supportingmanydatacombinations
Fittingtheprogramtotheuser.
RESTRICTIONSONOVERLOADING
Overloadedprogramswithparameterliststhatdifferonlybynamemustbecalledusingnamednotation.
Theparameterlistofoverloadedprogramsmustdifferbymorethanparametermode.
AlloftheoverloadedprogramsmustbedefinedwithinthesamePL/SQLscopeorblock.
Overloadedfunctionsmustdifferbymorethantheirreturntype.
IMPORTANTPOINTSABOUTSUBPROGRAMS
Whenastoredsubprogramiscreated,itisstoredinthedatadictionary.
Thesubprogramisstoredincompileformwhichisknownaspcodeinadditiontothesourcetext.
Thepcodehasallofthereferencesinthesubprogramevaluated,andthesourcecodeistranslatedintoa
formthatiseasilyreadablebyPL/SQLengine.
Whenthesubprogramiscalled,thepcodeisreadfromthedisk,ifnecessary,andexecuted.
Onceitreadsfromthedisk,thepcodeisstoredinthesharedpoolportionofthesystemglobalarea
(SGA),whereitcanbeaccessedbymultipleusersasneeded.
Likeallofthecontentsofthesharedpool,pcodeisagedoutofthesharedpoolaccordingtoaleast
recentlyused(LRU)algorithm.
Subprogramscanbelocal.
LocalsubprogramsmustbedeclaredinthedeclarativesectionofPL/SQLblockandcalledfromthe
executablesection.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

117/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Subprogramscannothavethedeclarativesectionseparately.
Storedsubprogramscanhavelocalsubprograms
Localsubprogramsalsocanhavelocalsubprograms.
Ifthesubprogramcontainsavariablewiththesamenameasthecolumnnameofthetablethenusethedot
methodtodifferentiate(subprogram_name.sal).
Subprogramscanbeinvalidated.
PROCEDURESVsFUNCTIONS
Proceduresmayreturnthroughoutandinoutparameterswhereasfunctionmustreturn.
Procedurescannothavereturnclausewhereasfunctionsmust.
Wecanusecallstatementdirectlyforexecutingprocedurewhereasweneedtodeclareavariableincase
offunctions.
Functionscanuseinselectstatementswhereasprocedurescannot.
Functionscancallfromreportsenvironmentwhereasprocedurescannot.
Wecanuseexecforexecutingprocedureswhereasfunctionscannot.
Functioncanbeusedindbms_outputwhereasprocedurecannot.
Procedurecallisastandaloneexecutablestatementwhereasfunctioncallisapartofanexecutable
statement.
STOREDVsLOCALSUBPROGRAMS
Thestoredsubprogramisstoredincompiledpcodeinthedatabase,whentheprocedureiscalleditdoes
nothavetobecompiled.Thelocalsubprogramiscompiledaspartofitscontainingblock.Ifthe
containingblockisanonymousandisrunmultipletimes,thesubprogramhastobecompiledeachtime.
Storedsubprogramscanbecalledfromanyblocksubmittedbyauserwhohasexecuteprivilegesonthe
subprogram.Localsubprogramscanbecalledonlyfromtheblockcontainingthesubprogram.
Bykeepingthestoredsubprogramcodeseparatefromthecallingblock,thecallingblockisshorterand
easiertounderstand.Thelocalsubprogramandthecallingblockareoneandthesame,whichcanleadto
partconfusion.Ifachangetothecallingblockismade,thesubprogramwillberecompiledasofthe
recompilationofthecontainingblock.
ThecompiledpcodecanbepinnedinthesharedpoolusingtheDBMS_SHARED_POOLPackage.This
canimproveperformance.Localsubprogramscannotbepinnedinthesharedpoolbythemselves.
Standalonestoredsubprogramscannotbeoverloaded,butpackagedsubprogramscanbeoverloaded
withinthesamepackage.
Localsubprogramscanbeoverloadedwithinthesameblock.
Ex1:
CREATE OR REPLACE PROCEDURE P IS
BEGIN
dbms_output.put_line('Stored subprogram');
END;
Output:
SQL> exec p
Stored subprogram

Ex2:
DECLARE
PROCEDURE P IS
BEGIN
dbms_output.put_line('Local subprogram');
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

118 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

END;
BEGIN
p;
END;
Output:
Local subprogram

COMPILINGSUBPROGRAMS
SQL>AlterprocedureP1compile
SQL>AlterfunctionF1compile
SUBPROGRAMSDEPENDECIES
Astoredsubprogramismarkedasinvalidinthedatadictionaryifithascompileerrors.
AstoredsubprogramcanalsobecomeinvalidifaDDLoperationisperformedononeofitsdependent
objects.
Ifasubprogramisinvalidated,thePL/SQLenginewillautomaticallyattempttorecompileinthenexttime
itiscalled.
IfwehavetwoprocedureslikeP1andP2inwhichP1dependsonP2.IfwecompileP2thenP1is
invalidated.
SUBPROGRAMSDEPENDENCIESINREMOTEDATABASES
WewillcallremotesubprogramusingconnectstringlikeP1@ORACLE
IfwehavetwoprocedureslikeP1andP2inwhichP1dependsonP2butP2wasinremotedatabase.Ifwe
compileP2itwillnotinvalidateP1immediatelybecausethedatadictionarydoesnottrackremote
dependencies.
Insteadthevalidityofremoteobjectsischeckedatruntime.WhenP1iscalled,theremotedatadictionary
isqueriedtodeterminethestatusofP2.
P1andP2arecomparedtoseeitP1needstoberecompiled,therearetwodifferentmethodsof
comparision
TimestampModel
SignatureModel
TIMESTAMPMODEL
Thisisthedefaultmodelusedbyoracle.
Withthismodel,thetimestampsofthelastmodificationsofthetwoobjectsarecompared.
Thelast_ddl_timefieldofuser_objectscontainsthetimestamp.
Ifthebaseobjecthasanewertimestampthanthedependentobject,thedependentobjectwillbe
recompiled.
ISSUESWITHTHISMODEL
Iftheobjectsareindifferenttimezones,thecomparisonisinvalid.
WhenP1isinaclientsidePL/SQLenginesuchasoracleforms,inthiscaseitmaynotpossibleto
recompileP1,becausethesourceforitmaynotbeincludedwiththeforms.
SIGNATUREMODEL
Whenaprocedureiscreated,asignatureisstoredinthedatadictionaryinadditiontothepcode.
Thesignatureencodesthetypesandorderoftheparametes.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

119/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

WhenP1iscompiledthefirsttime,thesignatureofP2isincluded.Thus,P1onlyneedstorecompiled
whenthesignatureofP2changes.
Inordertousethesignaturemodel,theparameterREMOTE_DEPENDENCIES_MODEmustbesetto
SIGNATURE.Thisisaparameterinthedatabaseinitializationfile.
THREEWAYSOFSETTINGTHISMODE
AddthelineREMOTE_DEPENDENCIES_MODE=SIGNATUREtothedatabaseinitializationfile.The
nexttimethedatabaseisstarted,themodewillbesettoSIGNATUREforallsessions.
Altersystemsetremote_dependencies_mode=signatureThiswillaffecttheentiredatabase(all
sessions)fromthetimethestatementisissued.YoumusthavetheALTERSYSTEMprivilegetoissue
thiscommand.
Altersessionsetremote_dependencies_mode=signatureThiswillonlyaffectyoursession
ISSUESWITHTHISMODEL
Signaturesdon'tgetmodifiedifthedefaultvaluesofformalparametersarechanged.
SupposeP2hasadefaultvalueforoneofitsparameters,andP1isusingthisdefaultvalue.Ifthedefault
inthespecificationforP2ischanged,P1willnotberecompiledbydefault.Theoldvalueforthedefault
parameterwillstillbeuseduntilP1ismanuallyrecompiled.
IfP1iscallingapackagedprocedureP2,andanewoverloadedversionofP2isaddedtotheremote
package,thesignatureisnotchanged.P1willstillusetheoldversion(notthenewoverloadedone)until
P1isrecompiledmanually.
FORWARDDECLERATION
Beforegoingtousetheprocedureinanyothersubprogramorotherblock,youmustdeclaretheprototypeof
theprocedureindeclarativesection.
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:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

120/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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

PRIVILEGESANDSTOREDSUBPROGRAMS
EXECUTEPREVILEGE
ForstoredsubprogramsandpackagestherelevantprivilegeisEXECUTE.
IfuserAhadtheprocedurecalledemp_procthenuserAgrantsexecuteprivilegeonproceduretouserB
withthefollowingcommand.
SQL>Grantexecuteonemp_proctouserB.
ThenuserBcanruntheprocedurebyissuing
SQL>ExecuserA.emp_proc
userAcreatedthefollowingprocedure
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;

userAgrantedexecuteprivilegetouserBusing
SQL>grantexecuteonptouserB
ThenuserBexecutedtheprocedure
SQL>ExecuserA.p
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

121/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

IfsupposeuserBalsohavingstudent2tablethenwhichtablewillpopulatewhetheruserA'soruserB's.
TheanswerisuserA'sstudent2tableonlybecausebydefaulttheprocedurewillexecuteundertheprivligeset
ofitsowner.
Theaboveprocedureisknownasdefiner'sprocedure.
HOWTOPOPULATEUSERB'sTABLE
OracleintroducesInvoker'sandDefiner'srights.
Bydefaultitwillusethedefiner'srights.
Aninvoker'srightsroutinecanbecreatedbyusingAUTHIDclausetopopulatetheuserB'stable.
Itisvalidforstandalonesubprograms,packagespecifications,andobjecttypespecificationsonly.
userAcreatedthefollowingprocedure
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;

ThengrantexecuteprivilegeonptouserB.
ExecutingtheprocedurebyuserB,whichpopulatesuserB'stable.
Theaboveprocedureiscalledinvoker'sprocedure.
Insteadofcurrent_userofauthidclause,ifyouusedefinerthenitwillbecalleddefiner'procedure.
STOREDSUBPROGRAMSANDROLES
wehavetwouserssakethandsudhainwhichsakethhasstudenttableandsudhadoesnot.Sudhaisgoingto
createaprocedurebasedonstudenttableownedbysaketh.Beforedoingthissakethmustgrantthe
permissionsonthistabletosudha.
SQL>connsaketh/saketh
SQL>grantallonstudenttosudha
thensudhacancreateprocedure
SQL>connsudha/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;

hereprocedurewillbecreated.
Ifthesameprivilegewasgrantedthrougharoleitwontcreatetheprocedure.
Examinethefollowingcode
SQL>connsaketh/saketh
SQL>createrolesaketh_role
SQL>grantallonstudenttosaketh_role
SQL>grantsaketh_roletosudha
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

122/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

thenconnsudha/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;

Theabovecodewillraiseerrorinsteadofcreatingprocedure.
ThisisbecauseofearlybindingwhichPL/SQLusesbydefaultinwhichreferencesareevaluatedin
compiletimebutwhenyouareusingarolethiswillaffectimmediately.
ISSUESWITHINVOKER'SRIGHTS
Inaninvoker'srightsroutine,externalreferencesinSQLstatementswillberesolvedusingthecaller's
privilegeset.
ButreferencesinPL/SQLstatementsarestillresolvedundertheowner'sprivilegeset.
TRIGGERS,VIEWSANDINVOKER'SRIGHTS
Adatabasetriggerwillalwaysbeexecutedwithdefiner'srightsandwillexecuteundertheprivilegesetof
theschemathatownsthetriggeringtable.
ThisisalsotrueforPL/SQLfunctionthatiscalledfromaview.Inthiscase,thefunctionwillexecute
undertheprivilegesetoftheview'sowner.
PACKAGES
Apackageisacontainerforrelatedobjects.
Ithasspecificationandbody.
Eachofthemisstoredseparatelyindatadictionary.
PACKAGESYNTAX
Create or replace package <package_name> is
-- package specification includes subprograms signatures,
cursors and global or public variables.
End <package_name>;
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>;

IMPORTANTPOINTSABOUTPACKAGES
Thefirsttimeapackagedsubprogramiscalledoranyreferencetoapackagedvariableortypeismade,
thepackageisinstantiated.
Eachsessionwillhaveitsowncopyofpackagedvariables,ensuringthattwosessionsexecuting
subprogramsinthesamepackageusedifferentmemorylocations.
Inmanycasesinitializationneedstoberunthefirsttimethepackageisinstantiatedwithinasession.This
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

123 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

canbedonebyaddinginitializationsectiontothepackagebodyafteralltheobjects.
Packagesarestoredinthedatadictionaryandcannotbelocal.
Packagedsubprogramshasanadvantageoverstandalonesubprogram.
Wheneveranyreferencetopackage,thewholepackagepcodewasstoredinsharedpoolofSGA.
Packagemayhavelocalsubprograms.
Youcanincludeauthidclauseinsidethepackagespecnotinthebody.
Theexecutionsectionofapackageisknowasinitializationsection.
Youcanhaveanexceptionsectionatthebottomofapackagebody.
Packagessubprogramsarenotinvalidated.
COMPILINGPACKAGES
SQL>AlterpackagePKGcompile
SQL>AlterpackagePKGcompilespecification
SQL>AlterpackagePKGcompilebody
PACKAGEDEPENDENCIES
Thepackagebodydependsonthesomeobjectsandthepackageheader.
Thepackageheaderdoesnotdependonthepackagebody,whichisanadvantageofpackages.
Wecanchangethepackagebodywithoutchangingtheheader.
PACKAGERUNTIMESTATE
Packageruntimestateisdifferforthefollowingpackages.
Seriallyreusablepackages
Nonseriallyreusablepackages
SERIALLYREUSABLEPACKAGES
ToforcetheoracletouseseriallyreusableversionthenincludePRAGMASERIALLY_REUSABLEinboth
packagespecandbody,
Examinethefollowingpackage.
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;
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

124/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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

Theabovepackagedisplaysthesameoutputforeachexecutioneventhoughthecursorisnotclosed.
Becausetheseriallyreusableversionresetsthestateofthecursoreachtimeitwascalled.
NONSERIALLYREUSABLEPACKAGES
Thisisthedefaultversionusedbytheoracle,
examinethefollowingpackage.
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
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

125 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Ename = MARTIN
SQL> exec pkg.emp_proc
Ename = BLAKE
Ename = CLARK
Ename = SCOTT
Ename = KING
Ename = TURNER

Theabovepackagedisplaysthedifferentoutputforeachexecutioneventhoughthecursorisnotclosed.
Becausethenonseriallyreusableversionremainsthestateofthecursoroverdatabasecalls.
DEPENDENCIESOFPACKAGERUNTIMESTATE
Dependenciescanexistsbetweenpackagestateandanonymousblocks.
Examinethefollowingprogram
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;

Connecttosecondsession,runthefollowingcode.
BEGIN
pkg.p;
END;

Theabovecodewilwork.
Gobacktofirstsessionandrecreatethepackageusingcreate.
Thenconnecttosecondsessionandrunthefollowingcodeagain.
BEGIN
pkg.p;
END;

Thisabovecodewillnotworkbecauseofthefollowing.
Theanonymousblockdependsonpkg.Thisiscompiletimedependency.
Thereisalsoaruntimedependencyonthepackagedvariables,sinceeachsessionhasitsowncopyof
packagedvariables.
Thuswhenpkgisrecompiledtheruntimedependencyisfollowed,whichinvalidatestheblockandraises
theoracleerror.
Runtimedependenciesexistonlyonpackagestate.Thisincludesvariablesandcursorsdeclaredina
package.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

126/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Ifthepackagehadnoglobalvariables,thesecondexecutionoftheanonymousblockwouldhave
succeeded.
PURITYLEVELS
Ingeneral,callstosubprogramsareprocedural,theycannotbecalledfromSQLstatements.
However,ifastandaloneorpackagedfunctionmeetscertainrestrictions,itcanbecalledduringexecutionof
aSQLstatement.
Userdefinedfunctionsarecalledthesamewayasbuiltinfunctionsbutitmustmeetdifferentrestrictions.
Theserestrictionsaredefinedintermsofpuritylevels.
Therearefourtypesofpuritylevels.
WNDSWritesNoDatabaseState
RNDSReadsNoDatabaseState
WNPSWritesNoPackageState
RNPSReadsNoPackageState
Inadditiontotheprecedingrestrictions,auserdefinedfunctionmustalsomeetthefollowingrequirementsto
becalledfromaSQLstatement.
Thefunctionhastobestoredinthedatabase,eitherstandaloneoraspartofapackage.
Thefunctioncantakeonlyinparametes.
Theformalparametersmustuseonlydatabasetypes,notPL/SQLtypessuchasbooleanorrecord.
Thereturntypeofthefunctionmustalsobeadatabasetype.
Thefunctionmustnotendthecurrenttransactionwithcommitorrollback,orrollbacktoasavepointprior
tothefunctionexecution.
Italsomustnotissueanyaltersessionoraltersystemcommands.
RESTRICT_REFERENCES
Forpackagedfunctions,however,theRESTRICT_REFERENCESpragmaisrequiredtospecifythepurity
levelofagivenfunction.
Syntax:
PRAGMARESTRICT_REFERENCES(subprogram_nameorpackage_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
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

127/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

update dept set dname ='aa';


return 'hello';
END FUN2;
END PKG;

Theabovepackagebodywillnotcreated,itwillgivethefollowingerros.
PLS00452:Subprogram'FUN1'violatesitsassociatedpragma
PLS00452:Subprogram'FUN2'violatesitsassociatedpragma
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;

Nowthepackagebodywillbecreated.
DEFAULT
IfthereisnoRESTRICT_REFERENCESpragmaassociatedwithagivenpackagedfunction,itwillnot
haveanypuritylevelasserted.
However,youcanchangethedefaultpuritylevelforapackage.
TheDEFAULTkeywordisusedinsteadofthesubprogramnameinthepragma.
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;

Theabovepackagebodywillnotcreated,itwillgivethefollowingerrosbecausethepragmawillapplytoall
thefunctions.
PLS00452:Subprogram'FUN1'violatesitsassociatedpragma
PLS00452:Subprogram'FUN2'violatesitsassociatedpragma
CREATE OR REPLACE PACKAGE BODY PKG IS
FUNCTION FUN1 return varchar IS
BEGIN
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

128 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

return 'hello';
END FUN1;
FUNCTION FUN2 return varchar IS
BEGIN
return 'hello';
END FUN2;
END PKG;

Nowthepackagebodywillbecreated.
TRUST
IftheTRUSTkeywordispresent,therestrictionslistedinthepragmaarenotenforced.
Rather,theyaretrustedtobetrue.
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;

Theabovepackagewillbecreatedsuccessfully.
IMPORTANTPOINTSABOUTRESTRICT_REFERENCES
Thispragmacanappearanywhereinthepackagespecification,afterthefunctiondeclaration.
Itcanapplytoonlyonefunctiondefinition.
Foroverloadfunctions,thepragmaappliestothenearestdefinitionpriortothepragma.
Thispragmaisrequiredonlyforpackagesfunctionsnotforstandalonefunctions.
ThePragmacanbedeclaredonlyinsidethepackagespecification.
Thepragmaischeckedatcompiletime,notruntime.
Itispossibletospecifywithoutanypuritylevelswhentrustorcombinationofdefaultandtrustkeywords
arepresent.
PINNINGINTHESHAREDPOOL
ThesharedpoolistheportionoftheSGSthatcontains,amongotherthings,thepcodeofcompiled
subprogramsastheyarerun.
Thefirsttimeastoredastoresubprogramiscalled,thepcodeisloadedfromdiskintothesharedpool.
Oncetheobjectisnolongerreferenced,itisfreetobeagedout.
ObjectsareagedoutofthesharedpoolusinganLRU(LeastRecentlyUsed)algorithm.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

129/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

TheDBMS_SHARED_POOLpackageallowsyoutopinobjectsinthesharedpool.
Whenanobjectispinned,itwillneverbeagedoutuntilyourequestit,nomatterhowfullthepoolgetsorhow
oftentheobjectisaccessed.
Thiscanimproveperformance,asittakestimetoreloadapackagefromdisk.
DBMS_SHARED_POOLhasfourprocedures
KEEP
UNKEEP
SIZES
ABORTED_REQUEST_THRESHOLD
KEEP
TheDBMS_SHARED_POOL.KEEPprocedureisusedtopinobjectsinthepool.
Syntax:
PROCEDUREKEEP(object_namevarchar2,flagchardefault'P')
Heretheflagrepresentsdifferenttypesofflagvaluesfordifferenttypesofobjects.
PPackage,functionorprocedure
QSequence
RTrigger
CSQLCursor
TObjecttype
JSJavasource
JCJavaclass
JRJavaresource
JDJavashareddata
UNKEEP
UNKEEPistheonlywaytoremoveakeptobjectfromthesharedpool,withoutrestartingthedatabase.Kept
objectsareneveragedoutautomatically.
Syntax:
PROCEDUREUNKEEP(object_namevarchar2,flagchardefault'P')
SIZES
SIZESwillechothecontentsofthesharedpooltothescreen.
Syntax:
PROCEDURESIZES(minsizenumber)
Objectswithgreaterthantheminsizewillbereturned.
SIZESusesDBMS_OUTPUTtoreturnthedata.
ABORTED_REQUEST_THRESHOLD
Whenthedatabasedeterminesthatthereisnotenoughmemoryinthesharedpooltosatisfyagivenrequest,it
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

13 0/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

willbeginagingobjectsoutuntilthereisenoughmemory.Itenoughobjectsareagedout,thiscanhavea
performanceimpactonotherdatabasesessions.TheABORTED_REQUEST_THRESHOLDcanbeusedto
remedythis.
Syntax:
PROCEDUREABORTED_REQUEST_THRESHOLD(threshold_sizenumber)
Oncethisprocedureiscalled,oraclewillnotstartagingobjectsfromthepoolunlessatleastthreshold_size
bytesisneeded.
DATAMODELFORSUBPROGRAMSANDPACKAGES
USER_OBJECTS
USER_SOURCE
USER_ERRORS
DBA_OBJECTS
DBA_SOURCE
DBA_ERRORS
ALL_OBJECTS
ALL_SOURCE
ALL_ERRORS
CURSORS
Cursorisapointertomemorylocationwhichiscalledascontextareawhichcontainstheinformation
necessaryforprocessing,includingthenumberofrowsprocessedbythestatement,apointertotheparsed
representationofthestatement,andtheactivesetwhichisthesetofrowsreturnedbythequery.Cursor
containstwoparts
Header
Body
Headerincludescursorname,anyparametersandthetypeofdatabeingloaded.
Bodyincludestheselectstatement.
Ex:
Cursorc(dnoinnumber)returndept%rowtypeisselect*fromdept
Intheabove
Headercursorc(dnoinnumber)returndept%rowtype
Bodyselect*fromdept

CURSORTYPES
Implicit(SQL)
Explicit
Parameterizedcursors
REFcursors
CURSORSTAGES
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

13 1/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Open
Fetch
Close
CURSORATTRIBUTES
%found
%notfound
%rowcount
%isopen
%bulk_rowcount
%bulk_exceptions
CURSORDECLERATION
Syntax:
Cursor<cursor_name>isselectstatement
Ex:
Cursorcisselect*fromdept
CURSORLOOPS
Simpleloop
Whileloop
Forloop
SIMPLELOOP
Syntax:
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:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

13 2/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Name = saketh
Name = srinu
Name = satish
Name = sudha

WHILELOOP
Syntax:
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

FORLOOP
Syntax:
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
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

13 3 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Name = sudha

PARAMETARIZEDCURSORS
Thiswasusedwhenyouaregoingtousethecursorinmorethanoneplacewithdifferentvaluesforthe
samewhereclause.
Cursorparametersmustbeinmode.
Cursorparametersmayhavedefaultvalues.
Thescopeofcursorparameteriswithintheselectstatement.
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 ||
' Loc = ' || v_dept.loc);
end loop;
close c;
END;
Output:
Dname = RESEARCH Loc = DALLAS

PACKAGEDCURSORSWITHHEADERINSPECANDBODYINPACKAGEBODY
cursorsdeclaredinpackageswillnotcloseautomatically.
Inpackagedcursorsyoucanmodifytheselectstatementwithoutmakinganychangestothecursorheader
inthepackagespecification.
Packagedcursorswithmustbedefinedinthepackagebodyitself,andthenuseitasglobalforthe
package.
Youcannotdefinethepackagedcursorinanysubprograms.
Cursordeclarationinpackagewithoutbodyneedsthereturnclause.
Ex:
CREATE OR REPLACE PACKAGE PKG IS
cursor c return dept%rowtype is select * from dept;
procedure proc is
END PKG;
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 = ' ||
v.dname || 'Loc = ' || v.loc);
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

13 4/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

end loop;
END PROC;
END PKG;
Output:
SQL> exec pkg.proc
Deptno = 10 Dname = ACCOUNTING
Deptno = 20 Dname = RESEARCH
Deptno = 30 Dname = SALES
Deptno = 40 Dname = OPERATIONS

Loc = NEW YORK


Loc = DALLAS
Loc = CHICAGO
Loc = BOSTON

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 = ' ||
v.dname || ' Loc = ' || v.loc);
end loop;
END PROC;
END PKG;
Output:
SQL> exec pkg.proc
Deptno = 30 Dname = SALES Loc = CHICAGO
Deptno = 40 Dname = OPERATIONS Loc = BOSTON

REFCURSORSANDCURSORVARIABLES
Thisisunconstrainedcursorwhichwillreturndifferenttypesdependsupontheuserinput.
Refcursorscannotbeclosedimplicitly.
Refcursorwithreturntypeiscalledstrongcursor.
Refcursorwithoutreturntypeiscalledweakcursor.
Youcandeclarerefcursortypeinpackagespecaswellasbody.
Youcandeclarerefcursortypesinlocalsubprogramsoranonymousblocks.
Cursorvariablescanbeassignedfromonetoanother.
Youcandeclareacursorvariableinonescopeandassignanothercursorvariablewithdifferentscope,
thenyoucanusethecursorvariableeventhoughtheassignedcursorvariablegoesoutofscope.
Cursorvariablescanbepassedasaparameterstothesubprograms.
Cursorvariablesmodesareinoroutorinout.
Cursorvariablescannotbedeclaredinpackagespecandpackagebody(excludingsubprograms).
Youcannotuserremoteprocedurecallstopasscursorvariablesfromoneservertoanother.
Cursorvariablescannotuseforupdateclause.
Youcannotassignnullstocursorvariables.
Youcannotcomparecursorvariablesforequality,inequalityandnullity.
Ex:
CREATE OR REPLACE PROCEDURE REF_CURSOR(TABLE_NAME IN VARCHAR) IS
type t is ref cursor;
c t;
v_dept dept%rowtype;
type r is record(ename emp.ename%type,job emp.job%type,
sal emp.sal%type);
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

13 5 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

v_emp r;
v_stud student.name%type;
BEGIN
if table_name = 'DEPT' then
open c for select * from dept;
elsif table_name = 'EMP' then
open c for select ename,job,sal from emp;
elsif table_name = 'STUDENT' then
open c for select name from student;
end if;
loop
if table_name = 'DEPT' then
fetch c into v_dept;
exit when c%notfound;
dbms_output.put_line('Deptno = ' || v_dept.deptno ||
' Dname = ' || v_dept.dname || ' Loc = ' || v_dept.loc);
elsif table_name = 'EMP' then
fetch c into v_emp;
exit when c%notfound;
dbms_output.put_line('Ename = ' || v_emp.ename ||
' Job = ' || v_emp.job || ' Sal = ' || v_emp.sal);
elsif table_name = 'STUDENT' then
fetch c into v_stud;
exit when c%notfound;
dbms_output.put_line('Name = ' || v_stud);
end if;
end loop;
close c;
END;
Output:
SQL> exec ref_cursor('DEPT')
Deptno = 10 Dname = ACCOUNTING Loc = NEW YORK
Deptno = 20 Dname = RESEARCH Loc = DALLAS
Deptno = 30 Dname = SALES Loc = CHICAGO
Deptno = 40 Dname = OPERATIONS Loc = BOSTON
SQL> exec ref_cursor('EMP')
Ename = SMITH Job = CLERK Sal = 800
Ename = ALLEN Job = SALESMAN Sal = 1600
Ename = WARD Job = SALESMAN Sal = 1250
Ename = JONES Job = MANAGER Sal = 2975
Ename = MARTIN Job = SALESMAN Sal = 1250
Ename = BLAKE Job = MANAGER Sal = 2850
Ename = CLARK Job = MANAGER Sal = 2450
Ename = SCOTT Job = ANALYST Sal = 3000
Ename = KING Job = PRESIDENT Sal = 5000
Ename = TURNER Job = SALESMAN Sal = 1500
Ename = ADAMS Job = CLERK Sal = 1100
Ename = JAMES Job = CLERK Sal = 950
Ename = FORD Job = ANALYST Sal = 3000
Ename = MILLER Job = CLERK Sal = 1300
SQL> exec ref_cursor('STUDENT')
Name = saketh
Name = srinu
Name = satish
Name = sudha
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

13 6/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

CURSOREXPRESSIONS
Youcanusecursorexpressionsinexplicitcursors.
YoucanusecursorexpressionsindynamicSQL.
YoucanusecursorexpressionsinREFcursordeclarationsandvariables.
Youcannotusecursorexpressionsinimplicitcursors.
Oracleopensthenestedcursordefinedbyacursorexpressionimplicitlyassoonasitfetchesthedata
containingthecursorexpressionfromtheparentoroutercursor.
Nestedcursorclosesifyoucloseexplicitly.
Nestedcursorcloseswhenevertheouterorparentcursorisexecutedagainorclosedorcanceled.
Nestedcursorcloseswheneveranexceptionisraisedwhilefetchingdatafromaparentcursor.
Cursorexpressionscannotbeusedwhendeclaringaview.
Cursorexpressionscanbeusedasanargumenttotablefunction.
Youcannotperformbindandexecuteoperationsoncursorexpressionswhenusingthecursor
expressionsindynamicSQL.
USINGNESTEDCURSORSORCURSOREXPRESSIONS
Ex:
DECLARE
cursor c is select ename,cursor(select dname from dept d
where e.empno = d.deptno) from emp e;
type t is ref cursor;
c1 t;
c2 t;
v1 emp.ename%type;
v2 dept.dname%type;
BEGIN
open c;
loop
fetch c1 into v1;
exit when c1%notfound;
fetch c2 into v2;
exit when c2%notfound;
dbms_output.put_line('Ename = ' || v1 || ' Dname = ' || v2);
end loop;
end loop;
close c;
END;

CURSORCLAUSES
Return
Forupdate
Wherecurrentof
Bulkcollect
RETURN
Cursorcreturndept%rowtypeisselect*fromdept
Or
Cursorc1isselect*fromdept
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

13 7/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Cursorcreturnc1%rowtypeisselect*fromdept
Or
Typetisrecord(deptnodept.deptno%type,dnamedept.dname%type)
Cursorcreturntisselectdeptno,dnamefromdept
FORUPDATEANDWHERECURRENTOF
Normally,aselectoperationwillnottakeanylocksontherowsbeingaccessed.
Thiswillallowothersessionsconnectedtothedatabasetochangethedatabeingselected.
Theresultsetisstillconsistent.Atopentime,whentheactivesetisdetermined,oracletakesasnapshotofthe
table.Anychangesthathavebeencommittedpriortothispointarereflectedintheactiveset.
Anychangesmadeafterthispoint,eveniftheyarecommitted,arenotreflectedunlessthecursorisreopened,
whichwillevaluatetheactivesetagain.
However,iftheFORUPDATEcaluseispesent,exclusiverowlocksaretakenontherowsintheactiveset
beforetheopenreturns.
Theselockspreventothersessionsfromchangingtherowsintheactivesetuntilthetransactioniscommitted
orrolledback.
Ifanothersessionalreadyhaslocksontherowsintheactiveset,thenSELECT...FORUPDATEoperation
willwaitfortheselockstobereleasedbytheothersession.
Thereisnotimeoutforthiswaitingperiod.TheSELECT...FORUPDATEwillhanguntiltheothersession
releasesthelock.Tohandlethissituation,theNOWAITclauseisavailable.
Syntax:
Select...from...forupdateofcolumn_name[waitn]
IfthecursorisdeclaredwiththeFORUPDATEclause,theWHERECURRENTOFclausecanbeusedinan
updateordeletestatement.
Syntax:
Wherecurrentofcursor
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;

BULKCOLLECT
Thisisusedforarrayfetches
Withthisyoucanretrievemultiplerowsofdatawithasingleroundtrip.
Thisreducesthenumberofcontextswitchesbetweenthepl/sqlandsqlengines.
Reducestheoverheadofretrievingdata.
Youcanusebulkcollectinbothdynamicandstaticsql.
Youcanusebulkcollectinselect,fetchintoandreturningintoclauses.
SQLengineautomaticallyinitializesandextendsthecollectionsyoureferenceinthebulkcollectclause.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

13 8 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Bulkcollectoperationemptiesthecollectionreferencedintheintoclausebeforeexecutingthequery.
Youcanusethelimitclauseofbulkcollecttorestrictthenoofrowsretrieved.
Youcanfetchintomultiblecollectionswithonecolumneach.
Usingthereturningclausewecanreturndatatotheanothercollection.
BULKCOLLECTINFETCH
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;
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

BULKCOLLECTINSELECT
Ex:
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

LIMITINBULKCOLLECT
Youcanusethistolimitthenumberofrowstobefetched.
Ex:
DECLARE
Type t is table of dept%rowtype;
nt t;
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

13 9/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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);
end loop;
END;
Output:
Dname = ACCOUNTING Loc = NEW YORK
Dname = RESEARCH Loc = DALLAS

MULTIPLEFETCHESININTOCLAUSE
Ex1:
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;
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

140/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

END;
Output:
Dname = ACCOUNTING
Dname = RESEARCH
Dname = SALES
Dname = OPERATIONS
Loc = NEW YORK
Loc = DALLAS
Loc = CHICAGO
Loc = BOSTON

RETURNINGCLAUSEINBULKCOLLECT
Youcanusethistoreturntheprocesseddatatotheouputvariablesortypedvariables.
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
no,name,marks bulk collect into nt2;
for v in nt2.first..nt2.last loop
dbms_output.put_line('Marks = ' || nt2(v));
end loop;
END;
Output:
Marks = 100
Marks = 200
Marks = 300
Marks = 400

POINTSTOREMEMBER
Cursornamecanbeupto30charactersinlength.
Cursorsdeclaredinanonymousblocksorsubprogramsclosesautomaticallywhenthatblockterminates
execution.
%bulk_rowcountand%bulk_exceptionscanbeusedonlywithforallconstruct.
Cursordeclarationsmayhaveexpressionswithcolumnaliases.
Theseexpressionsarecalledvirtualcolumnsorcalculatedcolumns.
SQLINPL/SQL
Theonlystatementsalloweddirectlyinpl/sqlareDMLandTCL.
BINDING
Bindingavariableistheprocessofidentifyingthestoragelocationassociatedwithanidentifierinthe
program.Typesofbinding
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

141/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Earlybinding
Latebinding
Bindingduringthecompiledphaseisearlybinding.
Bindingduringtheruntimephaseislatebinding.
Inearlybindingcompilephasewilltakelongerbecauseofbindingworkbuttheexecutionisfaster.
Inlatebindingitwillshortenthecompilephasebutlengthenstheexecutiontime.
PL/SQLbydefaultusesearlybinding.
BindingalsoinvolvescheckingthedatabaseforpermissionstoaccesstheobjectReferenced.
DYNAMICSQL
IfyouuseDDLinpl/sqlitvalidatesthepermissionsandexistenceifrequiresduringcompiletimewhich
makesinvalid.
WecanavoidthisbyusingDynamicSQL.
DynamicSQLallowsyoutocreateaSQLstatementdynamicallyatruntime.
TwotechniquesareavailableforDynamicSQL.
NativeDynamicSQL
DBMS_SQLpackage
USINGNATIVEDYNAMICSQL
USINGEXECUTEIMMEDIATE
Ex:
BEGIN
Execute immediate 'create table student(no number(2),name varchar(10))';
or
Execute immediate ('create table student(no number(2),name varchar(10))');
END;

USINGEXECUTEIMMEDIATEWITHPL/SQLVARIABLES
Ex:
DECLARE
v varchar(100);
BEGIN
v := 'create table student(no number(2),name varchar(10))';
execute immediate v;
END;

USINGEXECUTEIMMEDIATEWITHBINDVARIABLESANDUSINGCLAUSE
Ex:
DECLARE
v varchar(100);
BEGIN
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

142/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

v := 'insert into student values(:v1,:v2,:v3)';


execute immediate v using 6,'f',600;
END;

EXECUTINGQUERIESWITHOPENFORANDUSINGCLAUSE
Ex:
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

QUERIESWITHEXECUTEIMMEDIATE
Ex:
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;
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

143 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

BEGIN
Delete student where marks = marks;

-- this will delete all the rows


in the student table

END;

Thiscanbeavoidedbyusingthelabeledblocks.

<<my_block>>
DECLARE
Marks number(3) := 100;
BEGIN
Delete student where marks = my_block.marks;

-- delete rows which has a


marks of 100

END;

GETTINGDATAINTOPL/SQLVARIABLES
Ex:
DECLARE
V1 number;
V2 varchar(2);
BEGIN
Select no,name into v1,v2 from student where marks = 100;
END;

DMLANDRECORDS
Ex:
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;

RECORDBASEDINSERTS
Ex:
DECLARE
srow student%rowtype;
BEGIN
srow.no := 7;
srow.name := 'cc';
srow.marks := 500;
insert into student values srow;
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

144/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

END;

RECORDBASEDUPDATES
Ex:
DECLARE
srow student%rowtype;
BEGIN
srow.no := 6;
srow.name := 'cc';
srow.marks := 500;
update student set row=srow where no = srow.no;
END;

USINGRECORDSWITHRETURNINGCLAUSE
Ex:
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

FORALLSTATEMENT
Thiscanbeusedtogetthedatafromthedatabaseatoncebyreductingthenumberofcontextswitcheswhich
isatransferofcontrolbetweenPL/SQLandSQLengine.
Syntax:
Forall index_var in
[ Lower_bound..upper_bound |
Indices of indexing_collection |
Values of indexing_collection ]
SQL statement;

FORALLWITHNONSEQUENTIALARRAYS
Ex:
DECLARE
type t is table of student.no%type index by binary_integer;
ibt t;
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

145 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

BEGIN
ibt(1) := 1;
ibt(10) := 2;
forall i in ibt.first..ibt.last
update student set marks = 900 where no = ibt(i);
END;

Theaboveprogramwillgiveerrorlike'elementatindex[2]doesnotexists.Youcanrectifyitinoneofthe
twofollowingways.
USGAGEOFINDICESOFTOAVOIDTHEABOVEBEHAVIOUR
Ex:
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;

USGAGEOFINDICESOFTOAVOIDTHEABOVEBEHAVIOUR
Ex:
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;

POINTSABOUTBULKBINDS
PassingtheentirePL/SQLtabletotheSQLengineinonestepisknownasbulkbind.
Bulkbindsaredoneusingtheforallstatement.
IfthereisanerrorprocessingoneoftherowsinbulkDMLoperation,onlythatrowisrolledback.
POINTSABOUTRETURINGCLAUSE
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

146/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

ThiswillbeusedonlywithDMLstatementstoreturndataintoPL/SQLvariables.
Thiswillbeusefulinsituationslike,whenperforminginsertorupdateordeleteifyouwanttoknowthe
dataofthetablewhichhasbeeneffectedbytheDML.
WithoutgoingforanotherSELECTusingRETURNINGclausewewillgetthedatawhichwillavoida
calltoRDBMSkernel.
COLLECTIONS
Collectionsarealsocompositetypes,inthattheyallowyoutotreatseveralvariablesasaunit.
Acollectioncombinesvariablesofthesametype.
TYPES
Varrays
Nestedtables
Indexbytables(Associatearrays)
VARRAYS
Avarrayisdatatypeverysimilartoanarray.
Avarrayhasafixedlimitonitssize,specifiedaspartofthedeclaration.
Elementsareinsertedintovarraystartingatindex1,uptomaximumlenthdeclaredinthevarraytype.
Themaximumsizeofthevarrayis2gigabytes.
Syntax:
Type<TYPE_NAME>isvarray|varyingarray(<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));
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

147/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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,
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.trim;
dbms_output.put_line('After trim of one index, Count = ' || va.count);
va.trim(3);
dbms_output.put_line('After trim of three indexs, Count = ' || va.count);
dbms_output.put_line('AFTER TRIM, VARRAY ELEMENTS');
for i in va.first..va.last loop
dbms_output.put_line('va[' || i || '] = ' || va(i));
end loop;
va.delete;
dbms_output.put_line('After delete of entire varray,
Count = ' || va.count);
END;
Output:
Limit = 10
Count = 4
First Index = 1
Last Index = 4
Next Index = 3
Previous Index = 2
VARRAY ELEMENTS
va[1] = a
va[2] = b
va[3] = c
va[4] = d
Index 3 exists with an element c
After extend of one index, Count = 5
Index 5 exists with an element
Index 6 does not exists
After extend of two indexes, Count = 7
VARRAY ELEMENTS
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

148 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

va[1] = a
va[2] = b
va[3] = c
va[4] = d
va[5] =
va[6] =
va[7] =
AFTER ASSINGNING VALUES TO EXTENDED ELEMENTS, VARRAY ELEMENTS
va[1] = a
va[2] = b
va[3] = c
va[4] = d
va[5] = e
va[6] = f
va[7] = g
After extend of three indexes, Count = 10
VARRAY ELEMENTS
va[1] = a
va[2] = b
va[3] = c
va[4] = d
va[5] = e
va[6] = f
va[7] = g
va[8] = b
va[9] = b
va[10] = b
After trim of one index, Count = 9
After trim of three indexs, Count = 6
AFTER TRIM, VARRAY ELEMENTS
va[1] = a
va[2] = b
va[3] = c
va[4] = d
va[5] = e
va[6] = f
After delete of entire varray, Count = 0

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:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

149/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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 = '
|| va(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 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 = '
|| va(i).city);
end loop;
END;
Output:
Hno = 11 City = hyd
Hno = 22 City = bang
Hno = 33 City = kochi

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

15 0/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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

NESTEDTABLES
Anestedtableisthoughtofadatabasetablewhichhasnolimitonitssize.
Elementsareinsertedintonestedtablestartingatindex1.
Themaximumsizeofthevarrayis2gigabytes.
Syntax:
Type<TYPE_NAME>istableof<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
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

15 1/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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,
NESTED TABLE ELEMENTS');
for i in 1..nt.count loop
dbms_output.put_line('nt[' || i || '] = ' || nt(i));
end loop;
nt.extend(5,2);
dbms_output.put_line('After extend of five 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.trim;
dbms_output.put_line('After trim of one index, Count = ' || nt.count);
nt.trim(3);
dbms_output.put_line('After trim of three indexs, Count = ' || nt.count);
dbms_output.put_line('AFTER TRIM, NESTED TABLE ELEMENTS');
for i in 1..nt.count loop
dbms_output.put_line('nt[' || i || '] = ' || nt(i));
end loop;
nt.delete(1);
dbms_output.put_line('After delete of first index, Count = ' || nt.count);
dbms_output.put_line('NESTED TABLE ELEMENTS');
for i in 2..nt.count+1 loop
dbms_output.put_line('nt[' || i || '] = ' || nt(i));
end loop;
nt.delete(4);
dbms_output.put_line('After delete of fourth index, Count = ' || nt.count);
dbms_output.put_line('NESTED TABLE ELEMENTS');
for i in 2..3 loop
dbms_output.put_line('nt[' || i || '] = ' || nt(i));
end loop;
for i in 5..nt.count+2 loop
dbms_output.put_line('nt[' || i || '] = ' || nt(i));
end loop;
nt.delete;
dbms_output.put_line('After delete of entire nested table,
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

15 2/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Count = ' || nt.count);


END;
Output:
No limit to Nested Tables
Count = 4
First Index = 1
Last Index = 4
Next Index = 3
Previous Index = 2
NESTED TABLE ELEMENTS
nt[1] = a
nt[2] = b
nt[3] = c
nt[4] = d
Index 3 exists with an element c
After extend of one index, Count = 5
Index 5 exists with an element
Index 6 does not exists
After extend of two indexes, Count = 7
NESTED TABLE ELEMENTS
nt[1] = a
nt[2] = b
nt[3] = c
nt[4] = d
nt[5] =
nt[6] =
nt[7] =
AFTER ASSINGNING VALUES TO EXTENDED ELEMENTS, NESTED TABLE ELEMENTS
nt[1] = a
nt[2] = b
nt[3] = c
nt[4] = d
nt[5] = e
nt[6] = f
nt[7] = g
After extend of five indexes, Count = 12
NESTED TABLE ELEMENTS
nt[1] = a
nt[2] = b
nt[3] = c
nt[4] = d
nt[5] = e
nt[6] = f
nt[7] = g
nt[8] = b
nt[9] = b
nt[10] = b
nt[11] = b
nt[12] = b
After trim of one index, Count = 11
After trim of three indexs, Count = 8
AFTER TRIM, NESTED TABLE ELEMENTS
nt[1] = a
nt[2] = b
nt[3] = c
nt[4] = d
nt[5] = e
nt[6] = f
nt[7] = g
nt[8] = b
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

15 3 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

After delete of first index, Count = 7


NESTED TABLE ELEMENTS
nt[2] = b
nt[3] = c
nt[4] = d
nt[5] = e
nt[6] = f
nt[7] = g
nt[8] = b
After delete of fourth index, Count = 6
NESTED TABLE ELEMENTS
nt[2] = b
nt[3] = c
nt[5] = e
nt[6] = f
nt[7] = g
nt[8] = b
After delete of entire nested table, Count = 0

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:
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

15 4/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

15 5 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

INDEXBYTABLES
Anindexbytablehasnolimitonitssize.
Elementsareinsertedintoindexbytablewhoseindexmaystartnonsequentiallyincludingnegative
integers.
Syntax:
Type<TYPE_NAME>istableof<TABLE_TYPE>indexbybinary_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
index-by table, Count = ' || ibt.count);
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

15 6/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

END;
Output:
No limit to Index by Tables
Count = 4
First Index = -20
Last Index = 100
Next Index = 30
Previous Index = 1
INDEX BY TABLE ELEMENTS
ibt[-20] = b
ibt[1] = a
ibt[30] = c
ibt[100] = d
Index 30 exists with an element c
Index 50 does not exists
After delete of first index, Count = 3
After delete of index thirty, Count = 2
INDEX BY TABLE ELEMENTS
ibt[-20] = b
ibt[100] = d
After delete of entire index-by table, Count = 0

DIFFERENCESAMONGCOLLECTIONS
Varrayshaslimit,nestedtablesandindexbytableshasnolimit.
Varraysandnestedtablesmustbeinitializedbeforeassignmentofelements,inindexbytableswecan
directlyassignelements.
Varraysandnestedtablesstoredindatabase,butindexbytablescannot.
NestedtablesandindexbytablesarePL/SQLtables,butvarrayscannot.
Keysmustbepositiveincaseofnestedtablesandvarrays,incaseofindexbytableskeyscanbepositive
ornegative.
ReferencingnonexistentelementsraisesSUBSCRIPT_BEYOND_COUNTinbothnestedtablesand
varrays,butincaseofindexbytablesNO_DATA_FOUNDraises.
Keysaresequentialinbothnestedtablesandvarrays,nonsequentialinindexbytables.
Individualindexescanbedeletedinbothnestedtablesandindexbytables,butinvarrayscannot.
Individualindexescanbetrimmedinbothnestedtablesandvarrays,butinindexbytablescannot.
Individualindexescanbeextendedinbothnestedtablesandvarrays,butinindexbytablescannot.
MULTILEVELCOLLECTIONS
Collectionsofmorethanonedimensionwhichisacollectionofcollections,knownasmultilevelcollections.
Syntax:
Type<TYPE_NAME1>istableof<TABLE_TYPE>indexbybinary_integerType
<TYPE_NAME2>isvarray(<LIMIT>)|table|of<TYPE_NAME1>|indexbybinary_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
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

15 7/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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));
end loop;
end loop;
va.delete;
dbms_output.put_line('After delete of entire varray, Count = ' || va.count);
END;
Output:
Count = 4
Limit = 5
VARRAY ELEMENTS
va[1][1] = a
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

15 8 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

va[1][2] = b
va[1][3] = c
va[1][4] = d
va[2][1] = e
va[2][2] = f
va[2][3] = g
va[2][4] = h
va[3][1] = i
va[3][2] = j
va[3][3] = k
va[3][4] = l
va[4][1] = m
va[4][2] = n
va[4][3] = o
va[4][4] = p
First index = 1
Last index = 4
Next index = 3
Previous index = 2
Index 2 exists
After extend of one index, Count = 5
VARRAY ELEMENTS
va[1][1] = a
va[1][2] = b
va[1][3] = c
va[1][4] = d
va[1][5] = q
va[2][1] = e
va[2][2] = f
va[2][3] = g
va[2][4] = h
va[2][5] = r
va[3][1] = i
va[3][2] = j
va[3][3] = k
va[3][4] = l
va[3][5] = s
va[4][1] = m
va[4][2] = n
va[4][3] = o
va[4][4] = p
va[4][5] = t
va[5][1] = u
va[5][2] = v
va[5][3] = w
va[5][4] = x
va[5][5] = y
After trim of one index, Count = 4
After trim of two indexes, Count = 2
VARRAY ELEMENTS
va[1][1] = a
va[1][2] = b
va[2][1] = e
va[2][2] = f
After delete of entire varray, Count = 0

Ex2:
DECLARE
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

15 9/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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(
'nt[' || i || '][' || j || '] = ' || nt(i)(j));
end loop;
end loop;
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));
flag := nt.exists(2);
if flag = true then
dbms_output.put_line('Index 2 exists');
else
dbms_output.put_line('Index 2 exists');
end if;
nt.extend(2);
nt(1)(5) := 'Q';
nt(1)(6) := 'R';
nt(2)(5) := 'S';
nt(2)(6) := 'T';
nt(3)(5) := 'U';
nt(3)(6) := 'V';
nt(4)(5) := 'W';
nt(4)(6) := 'X';
nt(5)(1) := 'Y';
nt(5)(2) := 'Z';
nt(5)(3) := 'a';
nt(5)(4) := 'b';
nt(5)(5) := 'c';
nt(5)(6) := 'd';
nt(6)(1) := 'e';
nt(6)(2) := 'f';
nt(6)(3) := 'g';
nt(6)(4) := 'h';
nt(6)(5) := 'i';
nt(6)(6) := 'j';
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

160/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

dbms_output.put_line('After extend of one index, Count = ' || nt.count);


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(
'nt[' || i || '][' || j || '] = ' || nt(i)(j));
end loop;
end loop;
nt.trim;
dbms_output.put_line('After trim of one indexe, Count = ' || nt.count);
nt.trim(2);
dbms_output.put_line('After trim of two indexes, Count = ' || nt.count);
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(
'nt[' || i || '][' || j || '] = ' || nt(i)(j));
end loop;
end loop;
nt.delete(2);
dbms_output.put_line(
'After delete of second index, Count = ' || nt.count);
dbms_output.put_line('NESTED TABLE ELEMENTS');
loop
exit when v = 4;
for j in 1..nt.count+1 loop
dbms_output.put_line(
'nt[' || v || '][' || j || '] = ' || nt(v)(j));
end loop;
v := v + 1;
if v= 2 then
v := 3;
end if;
end loop;
nt.delete;
dbms_output.put_line('After delete of
entire nested table, Count = ' || nt.count);
END;
Output:
Count = 4
No limit to Nested Tables
NESTED TABLE ELEMENTS
nt[1][1] = A
nt[1][2] = B
nt[1][3] = C
nt[1][4] = D
nt[2][1] = E
nt[2][2] = F
nt[2][3] = G
nt[2][4] = H
nt[3][1] = I
nt[3][2] = J
nt[3][3] = K
nt[3][4] = L
nt[4][1] = M
nt[4][2] = N
nt[4][3] = O
nt[4][4] = P
First index = 1
Last index = 4
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

161/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Next index = 3
Previous index = 2
Index 2 exists
After extend of one index, Count = 6
NESTED TABLE ELEMENTS
nt[1][1] = A
nt[1][2] = B
nt[1][3] = C
nt[1][4] = D
nt[1][5] = Q
nt[1][6] = R
nt[2][1] = E
nt[2][2] = F
nt[2][3] = G
nt[2][4] = H
nt[2][5] = S
nt[2][6] = T
nt[3][1] = I
nt[3][2] = J
nt[3][3] = K
nt[3][4] = L
nt[3][5] = U
nt[3][6] = V
nt[4][1] = M
nt[4][2] = N
nt[4][3] = O
nt[4][4] = P
nt[4][5] = W
nt[4][6] = X
nt[5][1] = Y
nt[5][2] = Z
nt[5][3] = a
nt[5][4] = b
nt[5][5] = c
nt[5][6] = d
nt[6][1] = e
nt[6][2] = f
nt[6][3] = g
nt[6][4] = h
nt[6][5] = i
nt[6][6] = j
After trim of one indexe, Count = 5
After trim of two indexes, Count = 3
NESTED TABLE ELEMENTS
nt[1][1] = A
nt[1][2] = B
nt[1][3] = C
nt[2][1] = E
nt[2][2] = F
nt[2][3] = G
nt[3][1] = I
nt[3][2] = J
nt[3][3] = K
After delete of second index, Count = 2
NESTED TABLE ELEMENTS
nt[1][1] = A
nt[1][2] = B
nt[1][3] = C
nt[3][1] = I
nt[3][2] = J
nt[3][3] = K
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

162/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

After delete of entire nested table, Count = 0

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);
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

163 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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
of entire index-by table, Count = ' || ibt.count);
END;
Output:
Count = 0
No limit to Index-by Tables
INDEX-BY TABLE ELEMENTS
ibt([1][1] = a
ibt([4][5] = b
ibt([5][1] = c
ibt([6][2] = d
ibt([8][3] = e
ibt([3][4] = f
First Index = 1
Last Index = 8
Next Index = 4
Prior Index = 6
Count = 6
INDEX-BY TABLE ELEMENTS
ibt[1][1] = a
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
ibt([4][5] = b
ibt([5][1] = c
ibt([6][2] = d
ibt([8][3] = e
ibt([3][4] = f
Index 3 exists
After delete of first index, Count = 5
After delete of fourth index, Count = 4
INDEX-BY TABLE ELEMENTS
ibt([5][1] = c
ibt([6][2] = d
ibt([8][3] = e
ibt([3][4] = f
After delete of entire index-by table, Count = 0

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
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

164/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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(
'nt[' || i || '][' || j || '][' || k || '] = ' ||nt(i)(j)(k));
end loop;
end loop;
end loop;
END;
Output:
Count = 2
NESTED TABLE ELEMENTS
nt[1][1][1] = A
nt[1][1][2] = B
nt[1][2][1] = C
nt[1][2][2] = D
nt[2][1][1] = E
nt[2][1][2] = F
nt[2][2][1] = G
nt[2][2][2] = H

OBJECTSUSEDINTHEEXAMPLES
SQL>select*fromstudent
SNO
SNAME
---------- -------------1
saketh
2
srinu
3
divya
4
manogni

SMARKS
---------100
200
300
400

SQL>createorreplacetypeaddrasobject(hnonumber(2),cityvarchar(10))/
SQL>select*fromemploy

ENAME
JOB
ADDRESS(HNO, CITY)
---------- ---------- ----------------------------Ranjit
clerk
ADDR(11, 'hyd')
Satish
manager
ADDR(22, 'bang')
Srinu
engineer
ADDR(33, 'kochi')

ERRORHANDLING

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

165 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

PL/SQLimplementserrorhandlingwithexceptionsandexceptionhandlers.
Exceptionscanbeassociatedwithoracleerrorsorwithyourownuserdefinederrors.
Byusingexceptionsandexceptionhandlers,youcanmakeyourPL/SQLprogramsrobustandabletodeal
withbothunexpectedandexpectederrorsduringexecution.
ERRORTYPES
Compiletimeerrors
Runtimeerrors
ErrorsthatoccurduringthecompilationphasearedetectedbythePL/SQLengineandreportedbackto
theuser,wehavetocorrectthem.
RuntimeerrorsaredetectedbythePL/SQLruntimeenginewhichcanprogrammaticallyraiseandcaught
byexceptionhandlers.
Exceptionsaredesignedforruntimeerrorhandling,ratherthancompiletimeerrorhandling.
HANDLINGEXCEPTIONS
Whenexceptionisraised,controlpassestotheexceptionsectionoftheblock.
Theexceptionsectionconsistsofhandlersforsomeoralloftheexceptions.
Anexceptionhandlercontainsthecodethatisexecutedwhentheerrorassociatedwiththeexception
occurs,andtheexceptionisraised.
Syntax:
EXCEPTION
When exception_name then
Sequence_of_statements;
When exception_name then
Sequence_of_statements;
When others then
Sequence_of_statements;
END;

EXCEPTIONTYPES
Predefinedexceptions
Userdefinedexceptions
PREDEFINEDEXCEPTIONS
Oraclehaspredefinedseveralexceptionsthatcorrespondstothemostcommonoracleerrors.
Likethepredefinedtypes,theidentifiersoftheseexceptionsaredefinedintheSTANDARDpackage.
Becauseofthis,theyarealreadyavailabletotheprogram,itisnotnecessarytodeclaretheminthe
declarativesecion.
Ex1:
DECLARE
a number;
b varchar(2);
v_marks number;
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

166/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

167/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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

USERDEFINEDEXCEPTIONS
Auserdefinedexceptionisanerrorthatisdefinedbytheprogrammer.
UserdefinedexceptionsaredeclaredinthedeclarativesecionofaPL/SQLblock.
Justlikevariables,exeptionshaveatypeEXCEPTIONandscope.
RAISINGEXCEPTIONSUserdefinedexceptionsareraisedexplicitlyviatheRAISEstatement.

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

168 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Ex:
DECLARE
e exception;
BEGIN
raise e;
EXCEPTION
when e then
dbms_output.put_line('e is raised');
END;
Output:
e is raised

BULITINERRORFUNCTIONS
SQLCODEANDSQLERRM
SQLCODEreturnsthecurrenterrorcode,andSQLERRMreturnsthecurrenterrormessagetext
ForuserdefinedexceptionSQLCODEreturns1andSQLERRMreturns"userdeifnedexception".
SQLERRMwiiltakeonlynegativevalueexcept100.Ifanypositivevalueotherthan100returnsnon
oracleexception.
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));
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

169/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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_STACK
Thebuiltinfunction,likeSQLERRM,returnsthemessageassociatedwiththecurrenterror.
ItdiffersfromSQLERRMintwoways:
Itslengthisnotrestricteditwillreturnthefullerrormessagestring.
Youcannotpassanerrorcodenumbertothisfunctionitcannotbeusedtoreturnthemessageforarandom
errorcode.
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
ThisfunctionreturnsaformattedstringshowingtheexecutioncallstackinsideyourPL/SQLapplication.
Itsusefulnessisnotrestrictedtoerrormanagement
youwillalsofinditshandyfortracingtheexectutionofyourcode.
Youmaynotusethisfunctioninexceptionblock.
Ex:
BEGIN
dbms_output.put_line(dbms_utility.format_call_stack);
END;
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

170/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

Output:
----- PL/SQL Call Stack ----Object_handle
69760478

line_number
2

object_name
anonymous block

DBMS_UTILITY.FORMAT_ERROR_BACKTRACE
Itdisplaystheexecutionstackatthepointwhereanexceptionwasraised.
Thus,youcancallthisfunctionwithanexceptionsectionatthetoplevelofyourstackandstillfindout
wheretheerrorwasraiseddeepwithinthecallstack.
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_INITPRAGMA
Usingthisyoucanassociateanamedexceptionwithaparticularoracleerror.
Thisgivesyoutheabilitytotrapthiserrorspecifically,ratherthanviaanOTHERShandler.
Syntax:
PRAGMAEXCEPTION_INIT(exception_name,oracle_error_number)
Ex:
DECLARE
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

171/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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_ERROR
Youcanusethisbuiltinfunctiontocreateyourownerrormessages,whichcanbemoredescriptivethan
namedexceptions.
Syntax:
RAISE_APPLICATION_ERROR(error_number,error_message,,[keep_errors_flag])
TheBooleanparameterkeep_errors_flagisoptional.
IfitisTRUE,thenewerrorisaddedtothelistoferrorsalreadyraised.
IfitisFALSE,whichisdefault,thenewerrorwillreplacethecurrentlistoferrors.
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

EXCEPTIONPROPAGATION
Exceptionscanoccurinthedeclarative,theexecutable,ortheexceptionsectionofaPL/SQLblock.
EXCEPTIONRAISEDINTHEEXECUATABLESECTION
Exceptionsraisedinexecuatablesectioncanbehandledincurrentblockorouterblock.
Ex1:
DECLARE
e exception;
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

172/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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

EXCEPTIONRAISEDINTHEDECLARATIVESECTION
Exceptionsraisedinthedeclarativesecionmustbehandledintheouterblock.
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
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

173 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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

EXCEPTIONRAISEDINTHEEXCEPTIONSECTION
Exceptionsraisedinthedeclarativesecionmustbehandledintheouterblock.
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;
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

174/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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

RESTRICTIONS
Youcannotpassexceptionasanargumenttoasubprogram.
DATABASETRIGGERS
TriggersaresimilartoproceduresorfunctionsinthattheyarenamedPL/SQLblockswithdeclarative,
executable,andexceptionhandlingsections.
Atriggerisexecutedimplicitlywheneverthetriggeringeventhappens.
Theactofexecutingatriggerisknownasfiringthetrigger.
RESTRICTIONSONTRIGGERES
Likepackages,triggersmustbestoredasstandaloneobjectsinthedatabaseandcannotbelocaltoablock
orpackage.
Atriggerdoesnotacceptarguments.
USEOFTRIGGERS
Maintainingcomplexintegrityconstraintsnotpossiblethroughdeclarativeconstraintsenableattable
creation.
Auditinginformationinatablebyrecordingthechangesmadeandwhomadethem.
Automaticallysignalingotherprogramsthatactionneedstotakeplacewhenchagesaremadetoatable.
Performvalidationonchangesbeingmadetotables.
Automatemaintenanceofthedatabase.
TYPESOFTRIGGERS
DMLTriggers
InsteadofTriggers
DDLTriggers
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

175 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

SystemTriggers
SuspendTriggers
CATEGORIES
TimingBeforeorAfter
LevelRoworStatement
Rowleveltriggerfiresonceforeachrowaffectedbythetriggeringstatement.
RowleveltriggerisidentifiedbytheFOREACHROWclause.
Statementleveltriggerfiresonceeitherbeforeorafterthestatement.
DMLTRIGGERSYNTAX
Create or replace trigger <trigger_name>
Before | after on insert or update or delete
[For each row]
Begin
-- trigger body
End <trigger_name>;

DMLTRIGGERS
ADMLtriggerisfiredonanINSERT,UPDATE,orDELETEoperationonadatabasetable.
Itcanbefiredeitherbeforeorafterthestatementexecutes,andcanbefiredonceperaffectedrow,oronce
perstatement.
Thecombinationofthesefactorsdeterminesthetypesofthetriggers.
Theseareatotalof12possibletypes(3statements*2timing*2levels).

ORDEROFDMLTRIGGERFIRING
Beforestatementlevel
Beforerowlevel
Afterrowlevel
Afterstatementlevel
Ex:
Supposewehaveafollwingtable.
SQL>select*fromstudent
NO NAME
MARKS
----- ------- ---------1
a
100
2
b
200
3
c
300
4
d
400

Alsowehavetriggering_firing_ordertablewithfiring_orderasthefield.
CREATE OR REPLACE TRIGGER TRIGGER1
before insert on student
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

176/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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

CORRELATIONIDENTIFIERSINROWLEVELTRIGGERS
Insidethetrigger,youcanaccessthedataintherowthatiscurrentlybeingprocessed.
Thisisaccomplishedthroughtwocorrelationidentifiers:oldand:new.
AcorrelationidentifierisaspecialkindofPL/SQLbindvariable.
Thecoloninfrontofeachindicatesthattheyarebindvariables,inthesenseofhostvariablesusedin
embeddedPL/SQL,andindicatesthattheyarenotregularPL/SQLvariables.
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

177/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

ThePL/SQLcompilerwilltreatthemasrecordsoftypeTriggering_table%ROWTYPE.
Althoughsyntacticallytheyaretreatedasrecords,inrealitytheyarenot.:oldand:newarealsoknownas
pseudorecords,forthisreason.

TRIGGERING STATEMENT
-------------------INSERT
UPDATE

:OLD
---------------------all fields are NULL.

:NEW
-------------------------values that will be inserted
When the statement is completed.

original values for


new values that will be updated
the row before the
when the statement is completed.
update.
original values before
all fields are NULL.
the row is deleted.

DELETE

Ex:
Supposewehaveatablecalledmarkswithfieldsno,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*fromstudent
NO
---1
2
3
4
5

NAME
------a
b
c
d
e

MARKS
------100
200
300
400
500

SQL>select*frommarks
norowsselected
SQL>insertintostudentvalues(6,'f',600)
1rowcreated.
SQL>select*fromstudent
NO
---1
2
3
4
5
6

NAME
-----a
b
c
d
e
f

MARKS
------100
200
300
400
500
600

SQL>select*frommarks
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

178 /18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

NO OLD_MARKS NEW_MARKS
---- -------- --------600

SQL>updatestudentsetmarks=555whereno=5
1rowupdated.
SQL>select*fromstudent
NO
NAME
----- ------1
a
2
b
3
c
4
d
5
e
6
f

MARKS
------100
200
300
400
555
600

SQL>select*frommarks
NO OLD_MARKS NEW_MARKS
---- ---------- ----------600
5
500
555

SQL>deletestudentwhereno=2
1rowdeleted.
SQL>select*fromstudent
NO
---1
3
4
5
6

NAME MARKS
------ ---------a
100
c
300
d
400
e
555
f
600

SQL>select*frommarks
NO OLD_MARKS NEW_MARKS
---- ---------- ---------------600
5
500
555
2
200

REFERENCINGCLAUSE
Ifdesired,youcanusetheREFERENCINGclausetospecifyadifferentnamefor:oldane:new.
Thisclauseisfoundafterthetriggeringevent,beforetheWHENclause.
Syntax:
REFERENCING[oldasold_name][newasnew_name]
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

179/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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;

WHENCLAUSE
WHENclauseisvalidforrowleveltriggersonly.
Ifpresent,thetriggerbodywillbeexecutedonlyforthoserowsthatmeettheconditionspecifiedbythe
WHENclause.
Syntax:
WHENtrigger_condition
Wheretrigger_conditionisaBooleanexpression.
Itwillbeevaluatedforeachrow.The:newand:oldrecordscanbereferencedinsidetrigger_conditionaswell,
butlikeREFERENCING,thecolonisnotusedthere.
Thecolonisonlyvalidinthetriggerbody.
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;

TRIGGERPREDICATES
TherearethreeBooleanfunctionsthatyoucanusetodeterminewhattheoperationis.
Thepredicatesare
INSERTING
UPDATING
DELETING
Ex:
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');
h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

18 0/18 2

7/4/2016

plsqlH om e Oracle , PL/SQL M at erial

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

INSTEADOFTRIGGERS
InsteadoftriggersfireinsteadofaDMLoperation.
Also,insteadoftriggerscanbedefinedonlyonviews.
Insteadoftriggersareusedintwocases:
Toallowaviewthatwouldotherwisenotbemodifiabletobemodified.
Tomodifythecolumnsofanestedtablecolumninaview.

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

18 1/18 2

7/4/2016

h t t p://jobs4t im es.com /J4T/oracle/plsqlH om e.h t m l

plsqlH om e Oracle , PL/SQL M at erial

18 2/18 2

You might also like