SQL & PSQL
SQL & PSQL
Dual:
Duali
sadummytabl
eandi
tisadatadi
cti
onarytabl
e.
Example1
SELECT1+2F
ROMDUAL;
Output
1+2
3
Example2
SELECT'
Hel
lo'
,
1+NULL,
3FROMDUAL;
Output
‘
HELLO’1
+2 3
Hell
o3 3
Example3
SELECT*F
ROMDUAL;
Output
DUMMY
X
Null:
Nulli
saunassignedval
ueorunknownvalueorundefinedvalue.
Nulli
snotequaltozero.
Nulli
snotequaltospace.
Nulli
snotequaltounderscore.
Nulli
snotequaltoNull.
Nulli
snotequalto‘’
0+NULL Null
0-NULL Null
0*NULL Null
0/NULL Null
Nulli
salwaysgreaterthananynumberbecauseinascendingorderNul
lcomesl
astandin
descendi
ngorderitcomesf i
rstori
tismaximumi nascendingorder&mini
mumindescendi
ng
order.
Exampl e
Toi nsertnullvaluesi
ntotabl
e
INSERTALL
INTOT99VALU ES('
')
INTOT99VALU ES(NULL)
SELECT*F ROMDUAL;
DataTypes
Datatype Mi nsize Maxsize Defaul
tsize/
Def
aul
tformat
Number(p.s)Preci si
onis1
Scalari
s-84Preci si
onis38
Scalari
s1 27
char 1byte2000byte 1
nchar1byte2000byte 1
varchar2 1byte4000byte
nvarchar2 1byte4000byte
date 01 -January-4712BC31-December-9999dd-mom-yy
long 2gigabytes
blob 4gigabytes
clob 8gigabytes
timestamp
bfil
e
Long
1) AtablecancontainonlyoneLONGcol umn.
2) LONGcol umncannotappeari nwherecl ause,groupbycl
ause,
orderbycl
auseanddisti
nct.
3) Astoredf uncti
oncannotreturnaLONGval ue.
4) LONGcol umncannotbei ndexed.
5) I fatablehasLONGandLOBcol umns,thenyoucannotbindmorethan4000byteofdatafor
bothLONGandLOB.IfatablehaseitherLONGorLOBthenwecanbi ndmorethan4000byteofdata.
6) WecannotsetUNI QUEandPRIMARYKEYf orLONGcolumn.
Blob
Theabbrevi
ati
oni
sbi
naryl
argeobj
ect.
Iti
susedtostorei
mages(
i.
e..
gi
f,.
jpeg,
…etc.
)
Clob
Theabbrevi ationischaracterl argeobj ect.Iti susedtostoretextf i
les( i.
e..
xls,.
xml,.doc,
…
etc.¬)
DataDictionaryTabl es
1) DICTI
ON ARY–I tisusedtof i
ndlistofdatadi ctionarytabl esavailabl einoracle.
2) USER_OBJ ECTS-I tcontai nsl i
stofobj ectspresenti nthedatabase( i
.e.
,table,
index,vi
ew,
function,type,trigger, package, packagebody, l
ob,procedure,f unction,materi ali
zedvi ew,
sequence…etc. )
3) USER_TABLES–I tcontai nsl i
stoftabl esandgl obaltemporarytabl espresenti nthe
database.
4) USER_VI EWS-I tcontai nslistofvi ewspresenti nthedatabase.
5) USER_ERRORS–I tcontai nstheerroroccurredduri ngcreati ngobj ectl i
keprocedure,
packagebody, functi on..
.etc.
6) USER_TAB_COLUMNS–I tcontai nslistofcol umnspresenti ntheenti retableinthe
database.
7) USER_CONSTRAI NTS–I tcontai nsthel istofconstrai ntswhi chwascreatedbyal lusersi
n
thedatabase.
8) USER_I NDEXES–I tcontainsthel i
stofi ndexcreatedbyal lusersi nthedatabase.
9) USER_TRI GGERS-I tcontai nsthel i
stoftri ggerspresenti nthedatabase.
10) USER_S OURCE-I tcontai nstheenti rescri ptonobj ectlikeprocedure, package,package
body,
functi
on,triggerandtype.
11) USER_MVI EWS–I tcontai
nstheli
stofmaterial
izedvi
ewi nthedatabase.
12) USER_S EQUENCES-Itcontai
nstheli
stofsequencepresentinthedatabase.
13) USER_C ONS_COLUMNS
14) ALL_US ERS–I tcontai
nsli
stofuserswhocanlogini
ntodatabase.
TableParti
tioni
ng
Tableparti
tioni
samethodofsplittinganobj
ect(tabl
eorindex)i
ntoseparateparti
tions
basedonsomecriteri
a.Thecri
teriacanbedate,
numberorcharacter.
Example
Partiti
onedoncharacter
CREATETABLESALES_LIST(
SALESMAN_IDNUMBER(5),
SALESMAN_NAMEVARCHAR2( 30),
SALES_STATEVARCHAR2(20),
SALES_DATEDATE)
PARTITI
ONBYLIST(SALES_STATE) (
PARTITI
ONSALES_WESTVA LUES('MUMBAI',
'PUNE',
'GOA',
'NAGPUR',
'SURAT'),
PARTITI
ONSALES_EASTVAL UES('
KOLKATA',
'PATNA' ,
'RANCHI'
,
'JORHAT','
AGARTALA'
),
PARTITI
ONSALES_NORTHVA LUES('
DELHI'
,
'KANPUR','LUCKNOW','
AGRA','
MERUT'),
PARTITI
ONSALES_SOUTHVA LUES('
CHENNAI'
,'HYDREBAD' ,
'
COCHIN',
'BANGALORE'
,'
NELLORE'
)
);
Partiti
onedondate
CREATETABLESALES_RANGE(
SALESMAN_IDNUMBER(5),
SALESMAN_NAMEVARCHAR( 30),
SALES_AMOUNTNUMBER( 5),
SALES_DATEDATE)
PARTITI
ONBYRANGE(SALES_DATE) (
PARTITI
ONSALES_JAN2000VALUESLESSTHAN( TO_DATE( '
02/ 01/2000',
'MM/DD/YYYY'
)),
PARTITI
ONSALES_FEV2000VALUESLESSTHAN( TO_DATE( '
03/ 01/2000',
'MM/DD/YYYY'
))
);
I
ftablecontai
nsmorenumberofrowsthenqueri estakesmoretimetoexecuteaqueryand
tabl
ebecomeshardertomanager.Soi
nthatcaseweusetabl eparti
tioni
ngtoovercomethose
i
ssues.Wecanparti
tionTabl
e,I
ndex&Materi
alizedView.
Gl
obalTemporaryTabl
es
1) Dataintemporarytableisstoredintempsegmentsi nthetemptablespace.
2) Datai ntemporarytablesisautomatical
lydeletedattheendofthedatabasesession,
evenifitendsabnormally.
3) Vi ewscanbecreatedagainsttemporarytablesandcombinationsoftemporaryand
permanenttabl es.
4) Temporarytabl escanhavetriggersassoci
atedwi ththem.
5) I ndexescanbecreatedontemporarytables.Thecontentoftheindexandthescopeof
theindexisthesameasthedatabasesessi on.
Syntax
Tocreateagl obaltemporarytable
CREATEGLOBALTEMPORARYTABLEtablename(
Column1datatype,
Column2datatype
);
Todropagl obaltemporarytable.
DROPTABLEGLB_TEM;
ONCOMMI TPRESERVEROWS
Thisindi
catesthatdatashouldbepresentti
llthesessi
onends
Exampl e
CREATEGLOBALTEMPORARYTABLEGLB_TEM(
ENONUMBER ,
GENDERCHAR(2)
)ONCOMMI TPRESERVEROWS;
ONCOMMI TDELETEROWS
Thisindicatesthatdatashoul
dbedeletedattheendofthi
stransacti
on.
‘ONCOMMI
TDELETE
ROWS’ i
sthedef aul
tone.
Exampl e
CREATEGLOBALTEMPORARYTABLEGLB_TEM(
ENONUMBER ,
GENDERCHAR(2)
)ONCOMMI TDELETEROWS;
RealTimeExample
Inrealti
meglobaltemporarytabl
eisusedtostoreadatasetthati
susedi
nmostofthe
queries.
Materi
ali
zedViews
Materi
ali
zedviewisadatabaseobj
ectsthatstoretheresul
tofaquery.I
tisaschemaobj
ect.
I
tcanbecalledassnapshots.
Materi
ali
zedvi
ewoccupiesspacei
ndatabase.
Exampl e
Tocreateamateri al i
zedview
CREATEMATE RI
ALI ZEDVI EWM1AS
SELECTEMPLOYEE_I D,FIRST_NAME,SALARYFROMEMPLWHEREEMPLOYEE_I
DBETWEEN1
00AND1
50;
Todropamateri al izedview
DROPMATERI ALIZEDVI EWM5;
Toref reshaparti cul armateri ali
zedview
EXECUTEDBMS_MVI EW. REFRESH('
M1 '
);
(or)
BEGIN
DBMS_MVI EW.REF RESH( M1 ,
'
C');
END;
/
Toref reshenti remateri al
izedview
Readonl ymateri alizedvi ew
Usercannotperf ormDMLoperati onsinreadonl
ymaterial
izedview.
Example
CREATEMATERIALI
ZEDVIEWM30AS
SELECTA,
BFROMT1 ;
Updatabl
emateri al
izedview
UsercanperformDML( I
nsert,
Update,
andDelete)inupdatabl
emateri
ali
zedvi
ew.Thechanges
madeusingDMLoperati oninmateri
ali
zedvi
ewwi llnotbechangedi
nbasetabl
e.
Example
CREATEMATE RIALI
ZEDVIEWM30F ORUPDATEAS
SELECTA,BFROMT1 ;
Writablemateri al
izedview
Usercanperf ormDML( I
nsert,
UpdateandDelete)inwri
tablemateriali
zedview.Thechanges
madeusi ngDMLoperati oni
nmaterializedvi
ewwi l
lnotbechangedinbasetable.
Ifyourefresha
materializedviewthenthechangesmadewi l
lnotbeupdatedinbasetablebutitgetslostin
materializedviewitself.
Typesofmateri alizedvi ew
1) PrimaryKeymateri al i
zedview
Thisisdefaultmateri alizedvi ew. Whenyoucreatethi stypeofmateri ali
zedviewthenthebase
tablemusth avepri marykey. Subquerycanal sobeusedi ncreatingmateri al
izedvi
ewandi ti
s
calledassub-querymateri ali
zedview.
2) Obj ectmateri alizedvi ew
Thisisbasedonobj ecttabl eandcreatedbyusi ng‘OFTYPE’clause.
3) ROWI Dmateri ali
zedvi ew
Thisiscreatedbasedonrowedoftherowsi nabasetabl e.
Exampl e
CREATEMATE R I
ALIZEDVIEWM30REF RESHWI THROWIDAS
SELECT*F ROMT5;
4) Compl exmateri alizedvi ew
Materializedviewi sconsi derascompl exwhenyoudorestri ctionsbyusingDISTI
NCT,
CONNECTBY,
UNIQUE,
INTERSECT,MI NUS,UNI ONALL,joi
ns,aggregatef unctions…etc.
Materializedviewkeywords
1) ONCOMMI T
Wheneveryousavependi ngchangesthenyoumateri al
izedviewwi llberefreshed
automati callyforthi sweuse‘ ONCOMMI T’.
Example
CREATEMATERI
ALIZEDVI
EWLOGONCOURSE;
CREATEMATERI
ALIZEDVI
EWM5REFRESHF ASTONCOMMI
TAS
SELECT*FROMCOURSE;
2) ONDEMAND
Whenyouuse‘ONDEMAND’thenmateri al
izedvi
ewmustberef
reshedeveryti
mebyuser.
Thi
sis
defaultone.
Example
CREATEMATERIALI
ZEDVIEWM7REF RESHONDEMANDA
S
SELECT*FROMCOURSE;
executeDBMS_MVIEW.REFRESH(
'M7');
3) REF RESHF AST
Thischeckf oranychangedmadeinlogi
fyestheni
tref
reshesamateri
ali
zedvi
eworel
sei
t
doesn’tref resh
Exampl e
CREATEMATE RI
ALIZEDVI
EWLOGONS1
;
CREATEMATE RI
ALIZEDVI
EWM22REFRESHF
ASTAS
SELECT*F ROMS1;
4) REF RESHCOMPLETE
Inthiswhenyouupdatemateriali
zedviewaf terupdatingbasetabl
e;theentiredatai
n
materiali
zedviewaredeletedandtheninsertoperationstartsinmaterial
izedview.
Example
CREATEMATERIALI
ZEDVI
EWM22REF RESHCOMPLETEAS
SELECTROWIDASR,
CNAMEFROMS1;
6) NEVERREF RESH
Ifyoudon’
twanttoref reshmateri
ali
zedviewthenuse‘
NEVERREF
RESH’
Example
CREATEMATERI
ALIZEDVI
EWM8NEVERREFRESHAS
SELECT*FROMCOURSE;
Materiali
zedViewLOG
Materiali
zedviewlogsareusedtotrackchanges(i
nsert,
updateanddel
ete)toatabl
e.
Purgingmateri
alizedvi
ewl ogs
Itshownoofchangesmadetoatabl e.I
fyourefreshmaterial
izedvi
ewthenthi
sgetstozero.
SELECTCOUNT(*
)FROMML OG$_S1;
Advantages
1) Youcancreatemateriali
zedvi
ewonanothermateri
ali
zedview.Sothati
treducesmore
networktraf fic.
2) I tcanbeeitherreadonl
y,wri
tabl
eorupdatabl
e.
3) Youcancreatemateri ali
zedvi
ewforjoi
nqueri
esandquiresthatcontai
naggregate
functions.
4) I treducesnetworktraffi
c.
RealTi
meExample
Thisi
susedwhenmorenumberofuservi
sitparticul
artabl
erepeatedlywhi
chwillmake
networktraf
fic.
Inthi
sscenari
omateri
ali
zedviewwi l
lbecreatedfromwhereusercanget
data.
I
ndex
I
tisusedtoi
mprovetheperf
ormanceofqueryretri
eval
.
I
ndexcanbeei
therUni
queorNon-Uni
quei
ndex
Uni
queIndex
Iti
screatedautomati
cal
lywhenauserdef
inesapri
mary/
uni
queconstrai
ntf
oracol
umn.
Non-uni
queIndex
Createdbytheusertospeeduptheretri
evalofrows.
Mai
ntai
nedbyoracl
eserver
Whentocreateindex
1. Whenatableislarge.
2. Whenmostofthequeri esareexpectedtoretrievelessthan4%ofrowsf
romthetabl
e.
3. Whenacol umncontainsawi derangeofvalues.
4. Whencol umnismostof tenusedasaconditioninaquery.
5. Whenacol umncontainslargenumberofnul lvalues.
Whennottocreatei
ndex
1. Whenatablei
ssmall.
2. Whenmostofthequeri esareexceptedretri
evemorethan4%ofrowsf
romth
etabl
e.
3. Whencol umncontai
nsalargenumberofduplicates.
4. Whencol umnisnotmostoftenusedasconditioni
naquery.
5. Whenatabl ei
supdatedfrequently.
BitmapIndex
Createdforlowcardi
nali
tycol
umnthatcontai
nsl
essthan1
00uni
querecords.
Createi
twhen
youhavelotofdupli
cates.
Exampl e
Tocreateabi tmapindex
CREATEBITMAPINDEXIX1ONSTUDENT(
CID)
;
Todropabi tmapindex
DROPINDEXI
X1;
B-treeIndex
Createdforhighcardi
nal
itycol
umnthatcontai
nsmorethan1
00uni
querecords.
Exampl e
Tocreateai ndex
CREATEINDEXI X1ONSTUDENT( CID)
;
Todropai ndex
DROPINDEXIX1;
FunctionbasedI ndex
Exampl e
Tocreatef uncti onbasedindex
CREATEINDEXI X1ONSTUDENT( LOWER(
SNAME)
);
CREATEBITMA PI NDEXIX1ONSTUDENT(
LOWER(
SNAME
));
Todropf uncti onbasedi ndex
DROPINDEXIX1;
Composi
teI
ndex
Exampl e
Tocreatecomposi teindex
CREATEINDEXIX1ONSTUDENT( CI
D,
SNAME);
CREATEBITMAPI NDEXIX1ONSTUDENT(
CID,
SNAME)
;
Todropcomposi teindex
DROPINDEXIX1
;
Hints(/*+*/ )
Thisisusedtof orcethequerytorunparti
culari
ndexorf ul
ltabl
escan.
Example
Torunf ulltablescan
SELECT/*+F ULL(STUDENT)*
/SNAMEFROMSTUDENTWHERESNAME='
BRUCE'
;
Parsing
Oracleneedstoexecutesometaskbef oreexecutingSQLquery(whichisreceivedfromuser).
Thisprocessiscal l
ed
Parsing.
1) Syntacticcheck
Oracleparsesthesyntaxtocheckf ormi sspel
ledSQLkeywords.
2) Semanti ccheck
Oracleverifi
esal ltablenames&col umnnamef romthedatadictionarytableandchecktosee
ifuserisauthorizedtovi ewdata.
3) Opti mization
Oraclecreatesanexecuti onplanonschemastati stics.
Iftheentireabovetaskperf ormstheni tiscalledhardparsi
ng.I
fonl ysyntacticcheck&
semanticcheckperf ormtheni tiscall
edsof tparsing.Sof
tparsingoccurswhenyouuse
‘
cursors’.
Synonyms
Asynonymi sanal
ternativenameforobj ectsuchastables,
view,
sequences,
stored
proceduresandotherdatabaseobjects.Youcancreatesynonymforsynonym.I
tisobj
ectofa
database.
Toviewlistofsynonymsandwhichobj ectdoesitaffect
SELECT*FROMUSER_SYNONYMS;
Therearetwotypesofsynonyms. Theyare
i) Pri
vateSynonym
Thissynonymisaccessedwithi
ntheschema.
Thedef
aul
tonei
spri
vate.
Example
Tocreateprivatesynonym
CREATESYNONYMSTUDENT1F
ORSTUDENT;
Todropprivatesynonym
DROPSYNONYMSTUDENT1;
ii
) Publ icSynonym
Example
Tocreatepublicsynonym
CREATEPUBLI
CSYNONYMSTUDENT1F
ORSTUDENT;
Todroppubli
csynonym
DROPPUBLI
CSYNONYMSTUD
ENT1
;
Sequence
Itautomati call
ygeneratesuni
quenumber.I
tisaschemaobj
ect.
Itrepl
acestheappl
icati
on
code. I
tis
Mai nl
yusedf orgenerati
ngprimarykeycol
umnvalues.
Exampl e
Tocreatesequence
CreateSEQUEN CEseq
STARTwi th10
INCREMENTby2
MAXVALUE22;
Toal tersequence
AlterSEQUENCEseq
INCREMENTby1
MAXVALUE30;
Todropsequence
DropSEQUENCEseq;
Exampl e1 :
-
CreateSEQUEN CEseq
NOMI NVALUE
INCREMENTby2
NOMAXVALUE;
Exampl e2:-
CreateSEQUEN CEseq
NOMI NVALUE
MAXVALUE22;
Exampl e3:-
CreateSEQUEN CEseq
STARTwi th1
INCREMENTby2
NOMAXVALUE;
Exampl e4:-
CreateSEQUEN CEseq
MI NVALUE2
INCREMENTby2
NOMAXVALUE;
Exampl e5:-
CreateSEQUEN CEseq
STARTWI TH2
INCREMENTBY1
MAXVALUE1 0
NOCACHE
CYCLE;
Exampl e6:-
CreateSEQUEN CEseq
STARTWI TH1
INCREMENTBY1
MAXVALUE1 0
CACHE1 0;
Exampl e7:-
CREATESEQUENCEseq
STARTWI TH1
INCREMENTBY-1
MAXVALUE1 0;
Vi
ews
Vi
ewisvirtualtable.
Itlogi
cal
lyrepresentsasubsetofdataf
romoneormoretabl
e.
Wecancreateavi ewfromanotherview
Advantages
1) Tomakemorecomplexqueryl
ooksi
mpl
e.
2) Torestri ctdataaccess.
Exampl
e
Tocreateavi ew
CREATEVIEWV1AS
SELECTS.SNAME,C.
CNAME,F.F
NAMEF ROMCOURSEC,
STUDENTS,
FACULTYF
WHERES.CID=C.
CIDANDC.CI
D=F.CI
D;
Toalteravi ew
CREATEORREPLACEVIEWV1AS
SELECT*F ROMT1;;
Todropavi ew
DROPVIEWV1 ;
Toviewqueryofthevi ew
SELECT*F ROMUSER_VIEWS;
Toviewerrorsofavi ew
SELECT*F ROMUSER_ERRORS;
ReadOnly
Thiscanbeusedwhenyoudon’ twanttomani pul
atedatai
nvi
ew.
Example
CREATEORREPLACEVIEWV1AS
SELECTAF ROMT1WHEREA =1WI
THREADONLY;
UpdatableView
Hereyoucani nsert,update&deleterecordsbutthi
sacti
ononl
ybeperf
ormedonbasetabl
eor
atablefromwhi chthevi ewi
screated.
Example
CREATEORREPLACEVIEWV1AS
SELECTSNAMEF ROMSTUDENTWHERECI D=10;
CheckOption
Thisisusedwhenyouwanttoi nsertdatainviewsbychecki
ngcondi
tionf
romwherecl
ause.
Ifi
t
truetheni nsertoperati
ontakesplace.
Example
CREATEORREPLACEVIEWV1AS
SELECTAF ROMT1WHEREAIN(1,
3)WITHCHECKOPTION;
ForceView
Wecancreateavi ewwi thadummybasetabl
ewhi
chdoesnotexi
sti
nadatabase.
Thi
svi
ewwi
ll
behavingerrors
Example
CREATEORREPLACEFORCEVIEWV1AS
SELECT*FROMGREENS;
Restri
ctions
• Ifyouareusingpseudocolumnl i
keROWNUM,ROWIDandLEVELthenyoumustuseal
ias.
• Ifyouareusinggroupfunctionsthenyoumustuseal i
as.
Forupdatabl
eview
• Youcan’tuseORDERBYandGROUPBY.
• Youshouldnotuseanalyticalandaggregatefuncti
on.
• SubqueryinSELECTlist
Constrai
nts
Constraintsareoftwotypes. Theyare
i)TableLevelConstraints–Theconstraintscanbespecifi
edafteral
lthecol
umnsaredefi
ned.
Thisiscall
edtable-leveldefiniti
on.
ii
)ColumnLevelConstrai nts-Theconstraintscanbespecif
iedi
mmediatel
yafterthecol
umn
defini
tion.Thi
siscalledcolumn-leveldefi
niti
on.
1) Primarykey
Itisauniqueidentifier.
Ignoresnullvalues,
Itisentityintegrity.
Itwillnotacceptdupl i
cateval
ues.
Onlyoneprimarykeyi sall
owedinatabl
e.
Itautomati cal
lygeneratesuniquei
ndex.
Example
Toaddaprimarykeyusi ng‘create’command
CREATETABLEWORKERS(
WMNOVARCHAR2(6),
WMNAMEVARCHAR(20),
WMDESVARCHAR(20),
CONSTRAI
NTX1PRI
MARYKEY( WMNO)
);
Toaddaprimarykeyusi ng‘create’commandwi thoutusi
ngconstrai
ntname
CREATETABLEWORKERS(
WMNOVARCHAR2(6)PRIMARYKEY,
WMNAMEVARCHAR(20),
WMDESVARCHAR(20)
);
Toaddaprimarykeyusi ng‘alter’
command
ALTERTABLEWORKERSADDCONSTRAI NTX1PRIMARYKEY(WMNO);
Todropaprimarykeywhi chhasconstrai ntname
ALTERTABLEWORKERSDROPCONSTRAI NTX1;
Toenableaprimarykey
ALTERTABLEWORKERSENABLECONSTRAI NTX1 ;
Todisabl
eaprimarykey
ALTERTABLEWORKERSDISABLECONSTRAI NTX1;
2) Uni quekey
Iti
suniqueidentifi
er.
Itacceptsnullvaluesandcanacceptmorethan1nullvalue.
Iti
sentityintegrity.
Itautomaticallygeneratesuni
queindex.
Example
Toadduniquekeyusi ng‘
create’
commandwi thconstrai
ntname
CREATETABLEWORKERS(
WMNOVARCHAR2( 6),
WMNAMEVARCHAR( 20),
WMDESVARCHAR( 20),
CONSTRAI
NTX 1UNI
QUE(WMNO)
);
Toadduniquekeyusing‘create’commandwi thoutconstrai
ntname
CREATETABLEWORKERS(
WMNOVARCHAR2(6)UNIQUE,
WMNAMEVARCHAR(20),
WMDESVARCHAR(20)
);
Todropuniquekeyusing‘alter’
command
ALTERTABLEWORKERSADDCONSTRAI NTX1UNI
QUE(WMNO);
Todropuniquekey
ALTERTABLEWORKERSDROPCONSTRAI NTX1;
3) F oreignkey
Itisreferentiali ntegrity.
Itrefersapri mary( or)uniqueconstraintofanothertable.
Itacceptsnul lval ues.
Itacceptsdupl icateval ues.
Example
Tocreatef oreignkeyusi ng‘create’commandf romprimarykey
CREATETABLEWORKERS(
WMNOVARCHAR2( 6) ,
WMNAMEVARCHAR( 20) ,
WMDESVARCHAR( 20) ,
CONSTRAINTX1PRI MARYKEY( WMNO)
);
CREATETABLELOC(
WMNOVARCHAR2( 6) ,
WLNNUMBER( 20),
CONSTRAINTX2F OREI GNKEY(WMNO)REF ERENCESWORKERS(
WMNO)
);
Tocreatef oreignkeyusi ng‘create’commandf romuniquekey
CREATETABLEWORKERS(
WMNOVARCHAR2( 6) ,
WMNAMEVARCHAR( 20) ,
WMDESVARCHAR( 20) ,
CONSTRAINTX1UNI QUE(WMNO)
);
CREATETABLELOC(
WMNOVARCHAR2( 6) ,
WLNNUMBER( 20),
CONSTRAINTX2F OREI GNKEY(WMNO)REF ERENCESWORKERS(
WMNO)
);
Tocreatef oreignkeyusi ng‘alter’
command
ALTERTABLELOCADDCONSTRAI NTX2F OREI
GNKEY(WMNO)REFERENCESWORKERS(
WMNO)
Todropf oreignkey
ALTERTABLELOCDROPCONSTRAI NTX2;
4) Notnul l
I
tisdomai
nintegri
ty.
Ignoresnul
lval
ues.
Exampl e
Toaddnotnullusing‘
create’command
CREATETABLEWORKERS(
WMNOVARCHAR2(6)NOTNULL,
WMNAMEVARCHAR(20),
WMDESVARCHAR(20)
);
Toaddnotnullusing‘
alter’
command
ALTERTABLEWORKERSMODIFYWMNOVARCHAR2(
6)N
OTNULL;
Todropnotnull
ALTERTABLEWORKERSMODIFYWMNOVARCHAR2(
6)N
ULL;
5) Check
Iti
sdomai nintegrity.
Itshouldsatisfyaconditi
on.
Example
Toaddcheckconstrai ntusing‘
create’ commandwithconstraintname
CREATETABLEWORKERS(
WMNOVARCHAR2( 6),
WMNAMEVARCHAR( 20),
WMDESVARCHAR( 20),
WSALNUMBER( 8),
CONSTRAINTX1CHECK(WSALBETWEEN1 0000AND20000)
);
Toaddcheckconstrai ntusing‘
create’ commandwithoutconstraintname
CREATETABLEWORKERS(
WMNOVARCHAR2( 6),
WMNAMEVARCHAR( 20),
WMDESVARCHAR( 20),
WSALNUMBER( 8)CHECK(WSALBETWEEN1 0000AND20000)
);
Toaddcheckconstrai ntusing‘
alter’command
ALTERTABLEWORKERSADDCONSTRAI NTX1CHECK(WSALBETWEEN10000AND20000)
;
Todropcheckconstrai nt.
ALTERTABLEWORKERSDROPCONSTRAI NTX1 ;
Whenyouusenumber
CHECK(
WSALBETWEEN10000AND20000)
Whenyouusecharacter
CHECK(
WLOC='
CHENNAI
')
;
X1CHECK(
WMDESIN('
CHENNAI
'
,'
HYDREBAD'
))
Whenyouusedate
Example
Toseelistofcolumnsnames, datatype,tablename…etcinenti
redatabase
SELECT*FROMUSER_TAB_COLUMNS;
Toseelistofconstraintsnames,constrainttypes,
tabl
ename…etcinentiredatabase
SELECT*FROMALL_CONSTRAINTS;
Constrainttypesi
nALL_CONSTRAI
NTS
Primarykey P
Foreignkey R
Unique U
Notnull C
Check C
DataControlL
anguage
1) GRANT
Thiscommandi susedtoassi gnaprivil
egetotheuser.Youcanassi
gnSELECT,
INSERT,
UPDATE,
DELETE,REFERENCES ,ALTE RandINDEXprivil
egetouser.
Syntax
GRANTPRIVILEGEONOBJ ECTTOUSER
Example
Tograntsi nglepri vilege
GRANTSELECTONEMPLOYEESTOHR
Tograntmul tiplepri vil
ege
GRANTSELECT, I
NSERT, DELETEONEMPLOYEESTOHR
Tograntal lprivilege
GRANTALLONE MPLOYEESTOHR
Tograntal lprivilegetopubl ic(allusers)
GRANTALLONE MPLOYEESTOPUBLI C
Youcangi veprivilegeonf unctions&procedures
Syntax
Tograntpri vilegeonf unctionsorprocedures
GRANTEXECUTEONOBJ ECTTOUSER
2) REVOKE
Thiscommandi susedtorevokethepri vi
legesassi
gnedtotheuser.
Syntax
REVOKEPRIVI
LEGEONOBJ ECTF ROMUSER
Example
Torevokesingl epri vilege
REVOKESELECTONT1F ROMHR
Torevokemul tiplepri vil
ege
REVOKESELECT, I
NSERT, DELETEONT1F ROMHR
Torevokeal lprivilege
REVOKEALLONT1F ROMHR
Torevokeal lprivilegetopubl i
c(allusers)
REVOKEALLONEMPLOYEESF ROMPUBLIC
Syntax
Torevokeprivil
egeonfuncti
onsorprocedures
REVOKEEXECUTEONOBJ
ECTFROMUSER
Transmi
ssi
onControlLanguage
1) COMMIT
Savesal
lpendi
ngchangespermanent.
Example
COMMIT;
2) SAVEPOI NT
Iti
samarker.Iti
susedtoi
denti
fyapointtowhi chyoucanrol
lbacklater.I
ftwosavepoint
havesamenamethenwhenyouroll
backwilldoneuntilthel
astoccurrenceofthesavepoint.
Example
SAVEPOI
NTA;
3) ROLLBACK
Discardallpendi
ngchanges
Exampl e
Todiscardallpendi
ngchanges
ROLLBACK;
Todiscardtoparticularsavepoi
nt
ROLLBACKTOB;
4) SETTR A
NSACTI
ON
Iti
susedtosetcurrenttransactiontoreadonlyandreadwri
te.Thisdosen’taffectsother
transacti
onbyotherusers.
Toendthistransactionuse‘
COMMI
T’or‘ROLLBACK’
.Nameisthe
transacti
onnamegivenbyuser.
Example1
SETTRANSACTI
ONREADONL
YNAME'TORENTO'
;
Example2
SETTRANSACTI
ONREADWRI
TENAME'TORENTO'
;
DataManipul
ati
onLanguage
Thesecommandusedtomanagedatawi
thi
nschemaobj
ects.
1) SELECT
Thiscommandi susedtoretri
evedataf
romthedatabase
Example
SELECT*F ROMT1;
2) I NSERT
Thiscommandi susedtoinsertdataintoatabl
e.
Exampl e
Toi nsertintotablewithspecif
yingcolumnname
INSERTINTOT1(A)VALUES(6);
Toi nsertintotablewithoutspecif
yingcol
umnname
INSERTINTOT1VALUES(5);
3) UPDATE
Thiscommandi
susedtoupdatedatai
natabl
e.
Example
Toupdateenti
rerowinatable
UPDATET1SETA=8;
Toupdateparticul
arrowinatabl
e
UPDATET1SETA=7WHEREA=6;
4) DELETE
Thiscommandi susedtoremoveoneormorerowsf
romatabl
e.I
tcanberol
lback.
Example
Todeleteallrowsf romatable
DELETEFROMT1;
Todeleteonerowf romatabl
e
DELETEFROMT1WHEREA=4;
5) MERGE
Mergei sanupdateplusinsert.I
twillbeupdatedwheni
tismatchedandwi
llbei
nsertedwhen
itisunmatched.
Exampl e
MERGE
INTOT2
USINGT1
ON( T1
.A=T2.A)
WHENMATCHED
THENUPDATE
SETT2.B=T1.B
WHENNOTMATCHED
THEN
INSERT(T2.
A,
T2.B)VALUES(T1
.A,
T1.
B);
DataDefi
niti
onLanguage
Thesecommandshelpyoutomanagethedatabasestructure.
WhenyouexecuteDDLcommands
thenautocommittakesplaceattheendoftransacti
on.Thel
istsofDDLCommandsare.
1) CREATE
Thiscommandi susedtocreatedatabaseanddatabaseobj
ects.
Example
Tocreatedatabase
CREATEDATABASEDB1;
Tocreateobj ectsi
nthedatabase
CREATETABLEL1(
ANUMBER( 4)
);
2) DROP
Thiscommandi susedtodropdatabaseanddatabaseobj
ects.
Example
Todropdatabase
DROPDATABASEDB1;
Todropobjectsinthedatabase
DROPTABLEL1;
3) ALTER
Thisal
lowsyoutorenameanexi sti
ngtableandI
tcanal
sobeusedtoadd,
modi
fy,
ordropa
columnfromanexi sti
ngtable.
Example
Toaddacolumntoatabl e
ALTERTABLEL1ADDBVARCHAR2(4)NOTNULL;
Todropacolumnf romatabl e
ALTERTABLEL1MODIFYBNUMBER(5);
Tomodifyacolumnf romatabl e
ALTERTABLEL1DROPCOLUMNB;
Torenameadatabaseobj ect
ALTERTABLEL1RENAMETOL2;
4) RENAME
Thiscommandi
susedtorenameobj
ecti
nthedatabase.
Example
RENAMEL60TOT1
;
5) TRUNCA TE
Itdeletesalldatafromthetable.Actuall
ytruncatedoesn’
tremovedatabutde-al
locates
wholeDatapagesandpoi nterstoindex.
Exampl e
TRUNCATETABLEL1;
I tismuchfaster.
Wecan’ tuseconditioni
fastatementcontainsTruncate.
Atri ggerdoesn’
tf i
reontruncate.
I tcannotberoll
edback.
6) COMMENTS
Example
Tocreatecommentoncolumn
COMMENTONCOLUMNEMPL.F
NAMEI
S'MAI
DONNAME'
;
Toaltercommentoncolumn
COMMENTONCOLUMNEMPL.F
NAMEI
S'MAI
DONNAMEISF
ATHERNAME'
;
Todropcommentoncolumn
COMMENTONCOLUMNEMPL.F
NAMEI
S''
;
Joi
ns
Selecti
ngdatafromtwoormoretabl
eiscall
edjoins.
Whenweuseal
iasi
tismuchf
aster.
Typesofjoi
nare
1) Equi
Joi
n
Toselectmatchedrowsf romtwoormoretabl
eiscal
ledequi
joi
n.I
tcanbecal
ledasi
nnerj
oin
ornaturaljoi
n(naturalj
oinfi
ndcommoncol
umnsfromboththetabl
e).
Example
Option1
SELECT
S.
SNAME,
C.
CNAME
FROM
STUDENTS,
COURSEC
WHERE
S.
CID=C.CI
D;
Option2
SELECT
S.
SNAME,
C.
CNAME
FROM
STUDENTSINNERJOINCOURSEC
ON
S.
CID=C.CI
D;
Option3
SELECT
S.
SNAME,
C.
CNAME
FROM
STUDENTSJOINCOURSEC
ON
S.
CID=C.CI
D;
Option4
SELECT
S.
SNAME,
C.
CNAME
FROM
STUDENTSNATURALJ OI
NCOURSEC;
2) OuterJ
oin
a) Lef tOuterJoin
Togetmatchedrecordf romboththetabl
eandunmatchedrecordf
roml
efttabl
e.
Example
Option1
SELECT
S.
SNAME,
C.
CNAME
FROM
STUDENTS,
COURSEC
WHERE
S.
CID=C.CI
D(+)
;
Option2
SELECT
S.
SNAME,
C.
CNAME
FROM
STUDENTSLEFTOUTERJOI
NCOURSEC
ON
S.
CID=C.CI
D;
b) Ri ghtOuterJoin
Togetmatchedrecordf romboththetabl
eandunmatchedrecordf
romri
ghttabl
e.
Example
Option1
SELECT
S.
SNAME,
C.
CNAME
FROM
STUDENTS,
COURSEC
WHERE
S.
CID(+)=C.
C I
D;
Option2
SELECT
S.
SNAME,
C.
CNAME
FROM
STUDENTSRIGHTOUTERJOI
NCOURSEC
ON
S.
CID=C.CI
D;
c) F ul
lOuterJoi
n
Togetbothmatchedandun-matchedrecordf
romboththetabl
e.
Example
SELECT
S.
SNAME,
C.
CNAME
FROM
STUDENTSFULLOUTERJOI
NCOURSEC
ON
S.
CID=C.CI
D;
3) CrossJ oin
ItisaCartesi
anproduct.Numberofrowsi nfi
rsttabl
eisj oi
nedwithnumberofrowsi nthe
secondtable.Cartesi
anproductisformedwhenuserignores‘WHERE’
clause.
Crossj
oinisused
bydeveloperstoperformperf ormancetesti
ng.
Exampl e
SELECT
S.SNAME,
C.CNAME
FR OM
STUDENTS,
COURSEC;
4) Sel f-J
oin
Joi
ningatabl
ewithi
tsel
fiscal
ledsel
f-j
oin.
Example
SELECT
E1.
FI
RST_NAMEENAME,
E2.
FIRST_NAMEMNAME
FROM
EMPLOYEESE1,
EMPLOYEESE2
WHERE
E1.
MANAGER_ID=E2.
EMPLOYEE_I
D;
5) Semi Joi n
Itreturnsrowf romf irsttabl ewhenoneormorerowmatchedf oundinsecondtabl e.
Diff
erencebetweensemi -joinandinnerj oini
sthatrowi nfirsttablewillbereturnedonl y
onceeveni fthesecondtabl econtainstwomatchesf romarowi nthefirsttable,onlyonecopy
oftherowwi llbereturned. Semi-joinsarewri ttenbyusing‘I
N’&‘EXI
XTS’constructs.
Example
Option1
SELECTC.CID,C.CNAME
FROMCOURSEC
WHEREC.CIDIN( SELECTDI STINCT(S.CI
D)F ROMSTUDENTSWHERES. CI
DISNOTNULL);
Option2
6) Anti J
oi n
Itreturnsrowf romf irsttabl ewhennomatchesf oundi
nsecondtabl e.Anti-joi
nsarewri tten
byusing‘NOTI N’&‘ NOTEXI STS’constructs.
Example
Option1
SELECTC.CID,C.CNAME
FROMCOURSEC
WHEREC.CIDNOTI N( SELECTDI STI
NCT(S.CID)FROMSTUDENTSWHERES. CI
DISNOTNULL);
Option2
SetOperators
Therearefoursetoperatori
nSQL.
TheyareUNI
ON,
UNI
ONALL,
INTERSECTandMI
NUS.
LetustaketwotablesT1andT2
T1 T2
1 1
2 2
3 3
4 5
1) UNI
ON
Displ
aysdatafrombothtabl
esel
imi
nati
ngdupl
icaterows.
Example
SELECTAFROMT1
UNION
SELECTAFROMT2;
2) UNI ONALL
Displ
aysdatafrombothtabl
eswi
thoutel
imi
nati
ngdupl
icaterowsandi
tisf
aster.
Example
SELECTAFROMT1
UNIONALL
SELECTAFROMT2;
3) I NTERSE
CT
Displaysdatawhi
chi
scommonl
ypresentbothth
etabl
e.
Exampl e
SELECTAF ROMT1
INTERSECT
SELECTAF ROMT2;
4) MI NUS
Displ
aysdatafromTable1whichi
snotpresenti
nTable2.
Example
SELECTAFROMT1
MINUS
SELECTAFROMT2;
Rules
Itworksf romtoptobottom.
Bothcolumndatatypeshouldbesame.
Numberofcol umnsi
nboththequerymustbesame.
SubQueri
es
Aqueryembeddedwi
thi
nanotherqueryi
scal
ledsubquery.
Therearetwotypesofsubquery
theyare
a) Si ngl
eRowSubquery
Whenasubqueryreturnsonerowtheni tiscal
ledsi
nglerowsubquery.
Example
SELECTFI
RST_NAME,
SALARYFROMEMPLOYEESWHERESALARY>(SELECTSALARYF
ROM
EMPLOYEESWHEREFI
RST_NAME='
Neena'
);
b) Mul tiRowSubquery
Whenasubqueryreturnsmorethanonerowi scall
edmul tirowsubquery.
Example
SELECTFIRST_NAME,SALARYF ROMEMPLOYEESWHERESALARY>ALL
(SELECTSALARYF ROMEMPLOYEESWHEREF IRST_NAME='David'
);
ScalarSubquery
Whenevera‘ Select’
clausef oll
owedbysubqueryi scal l
edscalarsubquery
Example
WheneveraS ELECT1+2+(SELECT3+4FROMDUAL)F ROMDUAL;
Inl
inevi
ew
Whenevera‘From’cl
ausef oll
owedbysubqueryiscal
ledInli
nevi
ewornamedsubqueryi
na
fromclauseiscal
ledInl
ineview.
Example
SELECTFI
RST_NAMEFROM( SELECTF
IRST_NAMEFROMEMPLOYEES
WHEREDEPARTMENT_I
D=90) ;
NestedSubquery
Whenevera‘Where’clausefollowedbysubqueryiscallednestedsubquery.
Herefi
rstinner
queryisexecutedthenouterquerywi llbeexecuted.I
tdoesn’thaveanyref
erencebetween
innerqueryandouterquery.Innerqueryrunsonlyonceforouterquery.
Example
SELECTMAX(SALARY)FROMEMPLOYEES
WHERESALARY<( SELECTMAX(SALARY)FROMEMPLOYEES);
Co-relatedSubquery
Whenthei nnerqueryhasref erencetoouterqueryiscall
edcorrel
atedsubquery.Hereouter
queryrunsf i
rstandtheni nnerqueryisexecuted.I
tisuserrowbyrowprocessing.Thei
nner
queryisexecutedoncef oreveryrowoftheouterquery. I
tisf
aster.
Example
SELECTSALARYFROMEMPLOYEESE1WHERE( 3-1
)=
(SELECTCOUNT(DI
STINCT(E2.
SALARY))FROMEMPLOYEESE2
WHEREE2.SALARY>E1 .
SALARY);
Rul
esf
orwritingsubquery
Subquerymustbeencloseinbrackets
Subquerycannotbeusedafterorderby
Whenweusemul ti-rowsubquerythenweneedtouserel
ati
onaloperatorsl
ikeI
N,ALL&
ANY.
PseudoCol
umns
1) SYSDATE
Thi
scommandi susedtodi
spl
aycurrentsystemdatei
nDD-MOM-YY
Example
SELECTSYSDATEF
ROMDUAL;
2) SYSTI MESTAMP
Thiscommandisusedtodi
splaycurrentsystemdate&ti
me.
Example
SELECTSYSTI
MESTAMPFROMDUAL;
3) USER
Thiscommandshowsyouthecurrentuseryouhavel
oggedi
n.
Example
SELECTUSERF
ROMDUAL;
4) UI D
Thiscommandshowsyouthecurrentuseri
dyouhavel
oggedi
n.
Example
SELECTUI
DFROMDUAL;
5) ROWNUM
Thiscommandi
susedtogeneraterownumberstarti
ngf
rom1andwi
llnotbestoredi
nthe
database.
Example
SELECTROWNUMF
ROMEMPLOYEES;
6) ROWI D
ROWIDisuni
queandgeneratedwhentherowi
sinserted.
Ithas18di
gitcharacters(
contai
ns
mixedorcharacter&numbers) .
Thi
scommandisusertodispl
ayrowid.
Example
SELECTROWIDFROMEMPLOYEES;
7) NEXTVA L
Thiscommandisusedtoshownextavai
labl
eval
uef
romsequencewhi
chcanbeused.
Example
SELECTSEQ1
0.N
EXTVALFROMDUAL;
8) CURRVAL
Thiscommandshowsthecurrentval
uef
romthesequencethathasbeenal
readyused.
Example
SELECTSEQ1
0.C
URRVALF
ROMDUAL;
9) LEVEL
Example
SELECTEMPLOYEE_I
D,FI
RST_NAME,
MANAGER_I
D,LEVELASSTAGEFROMEMPLOYEESSTARTWI
TH
MANAGER_I
DISNULLCONNECTBYPRI
OREMPLOYEE_ID=MANAGER_I
DORDERBYSTAGEASC
SQLF
uncti
ons
Condi
tionalF
uncti
onsorControlStatements
1) Case
Example
SELECTDEPARTMENT_ID,
CASE
WHENDEPARTMENT_ID=10THEN'
A'
WHENDEPARTMENT_ID=20THEN'
B'
ELSE'X'
END
FROMDEPARTMENTS;
2) Decode
Thiscommandissimi l
artoi f.
.then..else.
.Statement. I
fthedef aul
tstatementisomi
ttedthen
nullwil
lbeusedifnomatchesf ound.
Syntax
DECODE(
COLUMNNAME, SERACH,RESULT,SEARCH,RESULT,DEFAULT)
Example
SELECTDEPARTMENT_ID,DECODE(DEPARTMENT_I D,
10,
'MANAGER',
20,
'
ASSTMANAGER'
,
30,
'
PRO J
ECTMANAGER',
40,'
TEAMLEADER' ,
'OTHERS'
)F ROMDEPARTMENTS;
ComparisonFunctions
1) Greatest
Thi
scommandreturnsthegreatestval
uei
ntheargumentsl
ist.
Thi
scommandcancontai
none
ormorearguments.
Example
SELECTGREATE
ST(
EMPLOYEE_I
D,MANAGER_I
D,DEPARTMENT_I
D,SALARY,
COMMI
SSI
ON_PCT)F
ROM
EMPLOYEES;
2) Least
Thiscommandreturnstheleastvalueintheargumentsl ist.Thiscommandcancontai
noneor
morearguments.
Example
SELECTLEAST(
EMPLOYEE_I
D,MANAGER_I
D,DEPARTMENT_I
D,SALARY,COMMISSI
ON_PCT)F
ROMEMPLOYEES;
GeneralF
uncti
ons
1) NVL
Itacceptsexactlytwoarguments.I
fthefirstargumenti
snul
lthendi
spl
aythesecond
argumentel sedi
splaythefi
rstargument.
Example
SELECTNVL(COMMISSI
ON_PCT,
0)F
ROMEMPLOYEES;
2) NVL2
Itacceptsexactlythreearguments.I
fthef i
rstargumenti
snul
lthendi
spl
aythethi
rd
argumentelsedisplaythesecondargument.
Example
SELECTNVL2(COMMISSI
ON_PCT,
2,
1)FROMEMPLOYEES;
3) NULLI F
Itacceptsexactlytwoarguments.
Displ
aynulli
fboththeargumentsaresameel
sedi
spl
ay
thefirstargument
Example
SELECTNULLI
F(SALARY,
24000)F
ROMEMPLOYEES;
4) COALESCE
Itcancontaintwoormorenumberofargumentsanditreturnsthef
irstnotnul
lfromthe
argumentsl i
st.
Example
SELECTCOALESCE(
COMMI
SSI
ON_PCT,
SALARY)F
ROMEMPLOYEES;
AggregateF
uncti
onsorGroupF
uncti
ons
1) AVG
Thiscommandi susedtoretri
eveaverage.
Example
SELECTAVG(SALARY)F
ROMEMPLOYEES;
2) COUNT
Thiscommandi susedtodi splaythecount.
COUNT(COLUMN_NAME)–di splaysnumberofnotnullcol
umninparticul
arcolumn.
COUNT(*)–displaysnumberofrowi nthetabl
ewithoutel
iminati
ngnullcol
umnsorrows.
Example
SELECTCOUNT(SALARY)FR
OMEMPLOYEES;
3) MAX
Thiscommandi
susedtoretri
evemaximumnumberorsal
ary.
Example
SELECTMAX(
SALARY)F
ROMEMPLOYEES;
4) MI N
Thiscommandisusedtoretri
evemini
mumnumberorsal
ary.
Example
SELECTMIN(
SALARY)F
ROMEMPLOYEES;
5) SUM
Thiscommandtoretri evebysummingupal
ltherowsi
nparti
cul
arcol
umn.
Itworksonl
yifthe
columndatatypei snumber.
Example
SELECTSUM(SALARY)FROMEMPLOYEES;
Therearecertainrulesforwri ti
ngaggregatefunctions.
i
) Groupfunctionsacceptonl yoneargument.
i
i) Groupf unctionsignorenullvaluesi
ncludi
ngCOUNT(*)
i
ii) Whenevercol umnisf ol
lowedbygroupf unctionorgroupfunctionfol
lowedbycol umn
shoul
dhave‘groupby’
i
v) Thesegroupf unctionsSUM&AVGonl yworki nnumberandnoti ndateandcharacter.
v) The‘ *
’cannotbeusedexceptCOUNT.
vi) Whenyouarerestri cti
ngwithgroupfunctionsuse‘HAVI
NG’cl
ause.
NumberF
uncti
ons
1) ROUND
Thiscommandi susedtoroundthedecimalvalues.
Ifthedeci
malval
uei
sgreaterthanorequal
to.5thenitisroundedtonextvalueelseroundedtocurrentval
ue.
Example
SELECTROUND(1
57.7),
ROUND(
157.
5),
ROUND(157.
3)FROMDUAL;
Output
ROUND(157.
4)ROUND(157.
5)ROUND(
157.
7)
157 1 58 1 58
2) TRUNC
Thiscommandi susedtoroundthedecimalpoi
nttocurrentval
ue.
Example
SELECTTRUNC(
157.7),
TRUNC(
157.
5),TRUNC(
157.
4)FROMDUAL;
Output
TRUNC(1
57.7)TRUNC(157.
4)TRUNC(
157.5)
157 1 57 1 57
3) MOD
Thiscommandisusedtoshowtheremai
nder.
Example
SELECTMOD(
5,2),
MOD(2,
2)FROMDUAL;
Output
MOD(5,
2) MOD(
2,2)
1 0
DateF
uncti
ons
1) MONTHS_BETWEEN
Thiscommandacceptsexactl ytwoargumentsandi tisusedtoshowdi
fferenceinmonths
betweentwodates. Ifargument1i sgreaterthanargument2thenoutputwillbeinposi
tive
integerel
seoutputwi llbeinnegativeinteger.
Example
SELECTMONTHS_BETWEEN( SYSDATE,
'
22-AUG-13')F
ROMDUAL;
2) ADD_MONTHS
Thiscommandacceptsexactlytwoargumentsanditi
susedforaddi
ngmonthstocurrentdate.
Example
SELECTADD_MONTHS(
SYSDATE,
12)
,ADD_MONTHS(
SYS
DATE,
-12)F
ROMDUAL;
3) NEXT_DAY
Thiscommandacceptsexactlytwoargumentsandi
tisusetoshowonwhi
chdatethenextday
comes.
Example
SELECTNEXT_DAY(
SYSDATE,
'
FRI
DAY'
)FROMDUAL;
4) LAST_DAY
Thiscommandacceptsexactlytwoargumentsandi
tisusedtoshowl
astdayofamonth.
Example
SELECTLAST_DAY(
SYSDATE)F
ROMDUAL;
CaseMani
pul
ati
onF
uncti
ons
1) UPPER
Thiscommandcanacceptonl yoneargumentanddi
spl
aysi
nuppercasef
ormat.
Example
SELECTUPPER(F
IRST_NAME)F
ROMEMPLOYEES;
2) LOWER
Thiscommandcanacceptonlyoneargumentanddi
spl
aysi
nlowercasef
ormat.
Example
SELECTLOWER(
FIRST_NAME)F
ROMEMPLOYEES;
3) I NITCAP
Thiscommandcanacceptoneargumentanddi
spl
ayf
irstcharacteri
ncapi
tal
.
Example
SELECTINI
TCAP(SNAME)F
ROMSTUDENT;
CharacterMani
pul
ati
onF
uncti
on
1
) CONCAT
Thiscommandacceptsexactl ytwoargumentsanddisplaystheresul
tbyconcatenati
ngthe
twoarguments.
Example
SELECTCONCAT(
FIRST_NAME,
LAST_NAME)FROMEMPLOYEES;
2) LENGTH
Thiscommandcanacceptonl
yoneargumentanddi
spl
aysthel
engthofthestri
ng.
Example
SELECTLENGTH
(FI
RST_NAME)F
ROMEMPLOYEES;
3) REPLACE
Thiscommandcanacceptexactl ytwoorthreeargumentsandhelpstorepl
acesthecharacter.
REPLACE(
FIRST_NAME,
'
e',
'x'
)–Here‘e’i
sreplacedwith‘
x’
.
REPLACE(
FIRST_NAME,
'
e')–Here‘e’i
sremoved.
Example
SELECTFI
RST_NAME,REPLACE(
FIRST_NAME,
'
e',
'x'
)FROMEMPLOYEES;
SELECTFI
RST_NAME,REPLACE(
FIRST_NAME,
'
e')FROMEMPLOYEES;
4) REVERSE
Thiscommandacceptsexactl
yoneargumentanddi
spl
aythestri
ngi
nreverseorder.
Example
SELECTREVERSE(
SNAME)F
ROMSTUDENT;
5) TRANSA LATE
Thiscommandreplacessequenceofstri ngwithanothersetofcharacter.Forexampl
eit
replaces1
stcharacterf rom stringtoreplacewith1stcharacterfromreplacementstri
ng
then2ndcharacterf rom stringtoreplacewith2ndcharacterf romrepl
acementstringsoon.
Example
SELECTTRANS
LATE('
1ABC23',
'
123'
,'
456')FROMDUAL;
6) LPAD
Thiscommandcanacceptexactl ytwoorthreeargumentsand
LPAD(SNAME,
10,'
@')–hereifthestringlessthan10charactersthenremai
ningcharacteri
s
fil
ledby‘@’inlefthandsideanddispl
aysexact10characters.
LPAD(SNAME,
5)–Hereitdisplaythestringonl
yupto5characters.
Exampl e
SELECTLPAD(SNAME,
10,
'
@' )FROMSTUDENT;
SELECTLPAD(SNAME,
5)FROMSTUDENT;
7) RPAD
Thiscommandcanacceptexactl ytwoorthreeargumentsand
RPAD(SNAME,
10,'
@' )–hereifthestringlessthan10charactersthenremai
ningcharacteri
s
fil
ledby‘@’inrighthandsideanddisplaysexact10characters.
RPAD(SNAME,
5)–Herei tdisplaythestringonlyupto5characters.
Exampl e
SELECTRPAD(SNAME,10,
'
@' )FROMSTUDENT;
SELECTRPAD(SNAME,5)FROMSTUDENT;
8) LTRI
M
Thiscommandi
susedtoremovespeci alcharacterorcharacteronl
efthandsi
de.
Example
SELECTLTRI
M('
**
**HELLO*
*WORLD*
***
',
'
*'
)FROMDUAL;
9) RTRI M
Thiscommandi
susedtoremovespeci alcharacterorcharacteronri
ghthandsi
de.
Example
SELECTRTRI
M('
**
**HELLO*
*WORLD*
***
',
'
*'
)FROMDUAL;
10) TRI M
Thiscommandi
susedtoremovespecialcharacterorcharacteronbothl
eft&ri
ghth
andsi
de.
Example
SELECTTRI
M('
*'
FROM'
***
*HELLO*
*WORLD**
**'
)FROMDUAL;
11
) SUBSTR
Thiscommandi susedtogetthestringofparticul
arlengthfromparti
cul
arstarti
ngposi
tion.
SUBSTR(SNAME,
1,
3)–Itisusedtoprint3characterstarti
ngfrompositi
on1
.
SUBSTR(SNAME,
-3)–itisusedtoprint3characterstarti
ngfromlastposi
tion.
Example
SELECTSUBSTR(SNAME,
1,
3)FROMSTUDENT;
SELECTSUBSTR(SNAME,
-3)FROMSTUDENT;
12) I NSTR
Thiscommandcanaccepttwotof ourarguments.Itisusedf
indtheposi
tionofoccurrenceofa
specifi
edcharacter.
Syntax
INSTR(
STRING1
,STRI
NG2,STARTI
NGPOSI
TION,
NthAPPERANCE)
Example
SELECTINSTR(
'TECHONTHENET'
,
'E'
)FROMDUAL;
SELECTINSTR(
'TECHONTHENET'
,
'E'
,
1,
2)FROMDUAL;
13) ASCI I
ThiscommandreturnsASCIIval
uesf orspeci
fiedcharacter.
Ifyoudecl
areawordtheni
t
returnstheASCII
valuesfor1stcharacter.
Example
SELECTASCI
I(
'C'
)FROMDUAL;
Anal
yti
calF
uncti
ons
1) RANK
Itprovidesranktorecordbasedonsomecolumnvalue.I
ncaseifatieof2recordoccursat
positi
onNth enthetworecordpositi
onswillbeNandgivesN+2tothenextrecord.
Example
SELECTEMPLOYEE_ID,
SALARY,
RANK(
)OVER(
ORDERBYSALARYDESC)FROMEMPLOYEES;
2) DENSE_RANK
Itprovi
desranktorecordbasedonsomecol
umnvalue.
Incasei
fatieof2recordoccursat
positi
onNthenthetworecordpositi
onswil
lbeNandgi
vesN+1tothenextrecord
Example
SELECTEMPLOYEE_I
D,SALARY,
DENSE_RANK(
)OVER(
ORDERBYSALARYDESC)F
ROM
EMPLOYEES;
3) ROW_NUMBER
Itgivesarunni
ngserialnumbertoarecord.
Exampl e
SELECTEMPLOYEE_I
D,SALARY,
ROW_NUMBER(
)OVER(
ORDERBYSALARYDESC)F
ROM
EMPLOYEES;
4) LEAD
Thiscommandcomputesanexpressiononnextrowisreturntheval uetothecurrentrow.
Example
SELECTFI
RST_NAME,
SALARY,
LEAD(
SALARY,
1,
0)OVER(
ORDERBYSALARYDESC)FROM
EMPLOYEES;
5) LAG
Thiscommandcomputesanexpressiononprevi
ousrowisreturnthevaluetothecurrentrow.
Example
SELECTFI
RST_NAME,
SALARY,
LAG(
SALARY,
1,
0)OVER(
ORDERBYSALARYDESC)F
ROM
EMPLOYEES;
6) F IRST_VALUE
Thiscommandpi cksthef i
rstrecordfromthepartitionafterdoingorderbyandf
irstrecord
arereturned.
Exampl e
SELECTEMPLOYEE_I D,HI
RE_DATE,
DEPARTMENT_I
D,FI
RST_VALUE(HI
RE_DATE)
OVER(PARTITI
O NBYDEPARTMENT_IDORDERBYHI
RE_DATE)FROMEMPLOYEESWHERE
EPARTMENT_I DIN(1
0,20,
30,
40,50)
;
7) LAST_VALUE
Thiscommandpicksthelastrecordf romthepartitionafterdoi
ngtheorderbyandl
ast
recordarereturned.
Example
SELECTEMPLOYEE_I
D,HI
RE_DATE,LAST_VALUE(HI
RE_DATE)OVER()F
ROMEMPLOYEES
WHEREDEPARTMENT_IDI
N(10,
20,30,
40,50)ORDERBYHIRE_DATE;
8) CUBE&ROLLUP
Boththesecommandi susedin‘groupby’clause.
Example
SELECTDEPARTMENT_I
D,SUM(SALARY)ASTOTALF ROMEMPLOYEES
WHEREDEPARTMENT_IDI
N( 1
0,20,
30,40)GROUPBYCUBE(
DEPARTMENT_I
D);
Output:-
- 58400
10 4400
20 1 9000
30 24900
40 6500
Example
SELECTDEPARTMENT_I
D,SUM(SALARY)ASTOTALFROMEMPLOYEES
WHEREDEPARTMENT_IDI
N( 1
0,20,
30,
40)GROUPBYROLLUP(
DEPARTMENT_I
D);
Output:-
10 4400
20 1 9000
30 24900
40 6500
- 58400
Operators
a)Conditionsymbol(or)Relati
onaloperator(
or)Comparisonoperator
= Equalto
> Greaterthan
< Lessth an
>= Greaterthanorequalto
<= Lesserthanorequalto
<>(or) !
= Notequalto
Theseoperatorscanhol donlysi
nglevaluesaf
terthisconditi
onalsymbol
.
Example1
SELECTEMPLOYEE_I
D,F
IRST_NAMEF
ROMEMPLOYEESWHERESALARY=24000;
Example2
SELECTEMPLOYEE_I
D,F
IRST_NAMEF
ROMEMPLOYEESWHERESALARY>17000;
Example3
SELECTEMPLOYEE_I
D,F
IRST_NAMEF
ROMEMPLOYEESWHERESALARY<24000;
Example4
SELECTEMPLOYEE_I
D,F
IRST_NAMEF
ROMEMPLOYEESWHERESALARY>=17000;
Example5
SELECTEMPLOYEE_I
D,F
IRST_NAMEF
ROMEMPLOYEESWHERESALARY<=17000;
Example6
SELECTEMPLOYEE_I
D,F
IRST_NAMEF
ROMEMPLOYEESWHERESALARY<>17000;
Example7
SELECTEMPLOYEE_I
D,F
IRST_NAMEF
ROMEMPLOYEESWHERESALARY!
=17000;
b)L
ogi
caloperator
i)AND
Thiscommandindicatesthatboththecondi
tionmustsatisfy.
Example
SELECTEMPLOYEE_ID,
FIRST_NAMEF
ROMEMPLOYEESWHERESALARY>14000
ANDSALARY<24000;
ii
)OR
Thiscommandi
ndi
catesthatei
theroneofthecondi
tionmustsati
sfy.
Example
SELECTEMPLOYEE_I
D,F
IRST_NAMEF
ROMEMPLOYEESWHERELAST_NAME='
Ki
ng'
ORLAST_NAME='Chen'
;
c)Relationaloperator
IN NOTIN
LIKE NOTLI KE
BETWE EN NOTBETWEEN
ISNULLISNOTNULL
ANY
ALL
i)I
N&NOTIN
Thiscommandcanholdoneormorevaluesafter‘I
N’operator.
Example1
SELECTFI
RST_NAMEFROMEMPLOYEESWHERESALARYIN(1
7000,24000);
Example2
SELECTFI
RST_NAMEFROMEMPLOYEESWHERESALARYNOTIN(17000,
24000)
;
ii
)LIKE&NOTL IKE
‘
S%’ –Itwillreturnastri ngstartingwithcapitalS.
‘
%S’ –Itwillreturnastri ngendi
ngwi thcapitalS.
‘
%S%’ –i twillreturnastringthati scontai
ningcapitalS(i
tcanbeatstarti
ng,
middl
eor
ending).
‘
500_%’ –Itwi llreturnastringthatisstartedby‘ 500’
.
‘
%_08’ –Itwil lreturnastringthatisendedby‘ 08’
.
Exampl e1
SELECTF I
RST_NAMEF ROMEMPLOYEESWHEREF I
RST_NAMELI KE'
S%';
Exampl e2
SELECTF I
RST_NAMEF ROMEMPLOYEESWHEREF I
RST_NAMENOTLI KE'
S%'
;
ii
i)BETWEEN&NOTBETWEEN
‘
BE TWEEN’themi ni
mumval ueordatemustbef i
rstandthenthenthemaxvalueordateshoul
d
follow.
Example1
SELECTSALARYF ROMEMPLOYEESWHERESALARYBETWEEN2400AND5000;
Example2
SELECTHIRE_DATEF ROMEMPLOYEESWHEREHI
RE_DATEBETWEEN'
21-SEP-89'
AND'
21-MAY-91
';
Example3
SELECTSALARYF ROMEMPLOYEESWHERESALARYNOTBETWEEN2400AND5000;
Example4
SELECTHIRE_DATEF ROMEMPLOYEESWHEREHI
RE_DATE
NOTBETWEEN' 21-SEP-89'
AND'21-MAY-91
';
iv)I
SNULL&I SNOTNULL
‘ISNULL’commandisusedtogetnullvaluecol
umnsand‘
I
SNOTNULL’
commandi
susedtogetnot
nullvaluecolumns.
Exampl e1
SELECTCOMMI SSI
ON_PCTFROMEMPLOYEESWHERECOMMI
SSI
ON_PCTI
SNULL;
Example2
SELECTCOMMI
SSI
ON_PCTF
ROMEMPLOYEESWHERECOMMI
SSI
ON_PCTI
SNOTNULL;
v)ANY
>ANY(17000,1
4000, 1
3500)–I tretrievessal
arygreaterthanl eastnumberpresenti n
parenthesis.
<ANY(17000,1
4000, 1
3500)–I tretrievessal
aryl esserthengreatestnumberpresenti n
parenthesis.
<>ANY( 1
7000,14000,13500)(or)!
=ANY( 1
7000,14000,13500)–I tretri evessal
aryl
esserthen,
greaterthanandequaltoval uepresentintheparenthesi s.
>=ANY( 1
7000,14000,13500)–Itretrievesthesal arygreaterthanorequaltothel eastval
ue
presentintheparenthesi s.
<=ANY( 1
7000,14000,13500)–Itretrievesthesal arylesserthanorequaltothegreatestval ue
presentintheparenthesi s.
=ANY(17000,1
4000, 1
3500)–Itretrievesthesal aryequaltotheval uepresenti
nthe
parenthesis.
Example1
SELECTSALARYF ROMEMPLOYEESWHERESALARY>ANY( 1
7000,14000, 1
3500) ;
Example2
SELECTSALARYF ROMEMPLOYEESWHERESALARY<ANY( 1
7000,14000, 1
3500) ;
Example3
SELECTSALARYF ROMEMPLOYEESWHERESALARY<>A NY( 17000,14000,13500) ;
Example4
SELECTSALARYF ROMEMPLOYEESWHERESALARY! =ANY( 17000,
14000, 13500) ;
Example5
SELECTSALARYF ROMEMPLOYEESWHERESALARY>=A NY( 17000,14000,13500);
Example6
SELECTSALARYF ROMEMPLOYEESWHERESALARY<=ANY( 17000,14000,13500) ;
Example7
SELECTSALARYF ROMEMPLOYEESWHERESALARY=ANY( 1
7000,14000, 1
3500) ;
vi)ALL
>AL L(1
7000, 1
4000,13500)–Itretrievessal arygreaterthengreatestnumberpresenti n
parenthesis.
<ALL( 1
7000, 1
4000,13500)–Itretrievessal arylesserthenl eastnumberpreseti nparenthesis.
<>ALL( 17000,14000,1
3500)(or)!=ALL( 17000,1
4000,13500)–I tretri evessal
arylesserthen
leastnumberi nparenthesisandsal arygreaterthengreatestnumberpresenti nparenthesis.
>=ALL( 1
7000, 1
4000,13500)–Itretri evessalarygreaterthanorequaltogreatestnumber
presenti nparenthesis.
<=ALL( 1
7000, 1
4000,13500)–Itretri evessalarylesserthanorequaltol eastnumberpresent
inparenthesis.
Example1
SELECTSALARYF ROMEMPLOYEESWHERESALARY>ALL( 17000,14000,13500) ;
Example2
SELECTSALARYF ROMEMPLOYEESWHERESALARY<ALL( 17000,14000,13500) ;
Example3
SELECTSALARYF ROMEMPLOYEESWHERESALARY<>A LL( 17000,14000,13500);
Example4
SELECTSALARYF ROMEMPLOYEESWHERESALARY! =ALL( 17000,14000,13500);
Example5
SELECTSALARYF
ROMEMPLOYEESWHERESALARY>=ALL(
17000,
14000,
13500)
;
Example6
SELECTSALARYF
ROMEMPLOYEESWHERESALARY<=ALL(
17000,
14000,
13500)
;
d)A
rithmeti coperator
+ Addition
- Subtracti on
* Multiplicati
on
/ Divi
sion
Orderofprecedence
Parenthesis
Multipli
cation
Divi
sion
Addition
Subtraction
CONVERSI
ONS
CLAUSES
Theseareth etypeofclausesare.
WHERE
Thisclauseisusedtorestrictnumberofrowstoreturnbyacondi
tion,
forj
oini
ngtwoormore
tables,restri
ctsviewsandmateriali
zedviews.
HAVING
GROUPBY
Thisclauseisusedtogrouptheresul tsbyoneormorecol umnsusedi ngroupby.
Iti
smost
oftenusedwhentherei saggregateorgroupf unctionsareusedi nquery.Thecol
umnyouare
specifyi
ngingroupbycl ausemustbei nselectli
stsamethi ngappliestosubquerywhere
columnnameshoul dbepresenti nthecurrentscopeofsel ectlistandnotinouterquery.
You
canuseanal yti
calfunction‘ROLLUP’and‘CUBE’i
ngroupbycl ause.
Exampl e
SELECTF I
RST_NAME,COUNT(*)ASNUMF ROMEMPLOYEESGROUPBYF I
RST_NAME;
SELECTDEPARTMENT_I D,
SUM( SALARY)ASTOTALF ROMEMPLOYEES
WHEREDEPARTMENT_I DIN(10,
20,30,
40)GROUPBYCUB E(DEPARTMENT_ID);
SELECTDEPARTMENT_I D,
SUM( SALARY)ASTOTALF ROMEMPLOYEES
WHEREDEPARTMENT_I DIN(10,
20,30,
40)GROUPBYROL LUP(DEPARTMENT_ID);
ORDERBY
Thisclauseisusedtospecifyinwhichordertheresultshouldbedisplayedeitherascending
(thisi
sdef ault)ordescendi
ngorder.Youcanuseoneormorecol umns, functionsandcolumn
positi
on( whichshouldbegreaterthan0)inorderbyclause.Wheneveryouusethi sclausethen
‘
SORT’operationtakesplace.Nul
lcomesl asti
nascendingorderandf i
rstindescendingorder.
Rules-
Ifyouusedi
sti
nctorgroupbycl
ausei
nsel
ectstatementthenorderbycol
umnmustbei
n
selectli
st.
Ifyouareusingsub-queryorderbymustbepl acedattheendofsubquery.
OrderbyclausepreventsaSELECTstatementf rombeinganupdatabl ecursor.
Example
SELECTCOMMI SSI
ON_PCTFROMEMPLOYEESORDERBYCOMMISSION_PCT,SALARY;
SELECTCOMMI SSI
ON_PCT+SALARYF
ROMEMPLOYEESORDERBYCOMMI SSION_PCT+SALARY;
SELECTCOMMI SSI
ON_PCTFROMEMPLOYEESORDERBYSALARYDESC;
SELECTFI
RST_NAME, COUNT(*)F
ROMEMPLOYEESGROUPBYF
IRST_NAMEORDERBYCOUNT(
*);
SELECTCOMMISSION_PCTF ROMEMPLOYEESORDERBY1;
SELECTSALARYFROMEMPLOYEESORDERBYF 2(SALARY)
;
WITH
Iti
sprocessedastemporarytabl eanditi
susedtosimpli
fycompl exqueri
es.
Example
WITHDEPT_COUNTAS( SELECTDEPARTMENT_ID,
COUN
T(*)ASDEPT_COUNTFROMEMPLOYEESGROUPBY
DEPARTMENT_ID)
SELECTE.FI
RST_NAME,D.DEPT_COUNT
FROMEMPLOYEESE, DEPT_COUNTD
WHEREE.DEPARTMENT_ID=D. DEPARTMENT_I
D
PLSQL:
PL/SQLisaprocedurall
anguageextensi
ontoSQLwithdesignedfeaturesofprogrammi ng
language.
Userscandeclarevari
ables,
cursorsandhandl
eerrors.PL/SQLgroupslogi
call
y
relatedSQLstatementsputtogetherinonesingl
eblockandsendtheenti reblocktothe
serverinonesingl
ecall.
Therebyreducingnetworktraffi
c.
Exampl
e:
BEGI
N
DBMS_OUTPUT.
PUT_LI
NE(
'HELLOWORLD'
);
END;
Output:
HELLOWORLD
Di
fferencebetweenPL/
SQLandSQL:
1
) SQLi
sexecutedonestatementatati
me.
PL/
SQLi
sexecutedasabl
ockofcode.
2) YoucanembedSQLi
naPL/
SQLprogrambutyoucannotembedPL/
SQLi
naSQLstatement.
3) SQLtel
lsthedatabasewhattodobutPL/
SQLtel
lthedatabasehowtodothi
ngs.
Theattri
buteofvari
abl
eare:
1
) %TYPE
Thi
sonei
susedtoretri
evedatatypeofsi
ngl
ecol
umnf
romatabl
e.
2) %ROWTYPE
Thisattri
buteisusedtoretrievedatatypeofenti
recolumnf romtable.
Hereyoudon’
thave
declaredvari
ablesforal
lthecolumnsinatableandyoudon’
thavetoupdatecodewh enyou
alterthecolumninatable.
Whenyouusethisth ememorywillbeusedforcreati
ngdatatype
forallthecolumns,
sousethisonlywhenyouareselecti
ngallcolumns.
3) RECORD
Recordsarecomposi
tedatatypewhichiscombi
nationofdi
fferentscal
ardatatypeli
kechar,
varchar,
number…etc.
Thisattri
buteisusedtoretri
eveenti
reroworspecifiedcol
umnsfrom
table.
Exampl
e:
TYPEGREENSI
SRECORD(
AVARCHAR(
20)
,BNUMBER(
20)
,CDATE)
;
4) PL/
SQLTABLE
I
tisanorderedcol
lecti
onofel
ementofthesamedatatype.Eachelementhasuni
quesubscript
numberwhichcani
denti
fytheposi
tion.
PL/
SQLtabl
eisunbounded.I
thassomeattributesthey
are
EXI
STS(
n)–Returntruei
fthenthel
ementi
spresent.
COUNT–I
tisusedtogettotalnumberofel
ementsi
nPL/
SQLtabl
e
F
IRST–I
tisusedtogetf
irsti
ndexorsubscri
ptval
ue.
LAST-I
tisusedtogetl
asti
ndexorsubscri
ptval
ue.
PRI
OR(
n)–I
treturnsthepri
ori
ndexnumberofn.
NEXT(
n)–I
treturnsthenexti
ndexnumberofn.
DELETE–Itisusedtodel
etetheallel
ements(
DELETE)
,parti
cul
arel
ements(
DELETE(
n))or
rangingel
ementsf rom&to(DELETE(m.
n))
.
Exampl
e:
TYPEGREENSI
STABLEOFNUMBERI
NDEXBYBI
NARY_I
NTEGER;
I
GREENS;
5) VARRAY
Varraystandsf
orvari
able-sizearray.Whenyoucreatevarrayyoumustdeclaremaximum
numberofcolumns.
Iti
ssimilartoPL/ SQLtabl
eandonlydi
fferencefromPL/SQLtabl
eisthat
youmustmentionsnoofcolumns.
Exampl
e:
TYPETNAMEI
SVARRAY(
3)OFVARCHAR2(
20)
;
I
TNAME;
EXCEPTI
ONS:
Excepti
onsareerrorhandl
ingacti
ontobeperf
ormedwhenerroroccurs.
Typesofexcepti
on
are
1
) Pre-Def
ined
Thi
scanbecall
edassystemdefinedexceptionornamedsystemexception.
PL/SQLpredef
ines
somecommonoracleerrorsasexcepti
ons.Thereis20pre-def
inedexcepti
ons.Theli
stofpre
defi
neexcepti
onare
SYS_I
NVALI
D_R
OWI
D -Excepti
onoccurswhenrow-i
dnotf
ound.
CURSOR_ALREADYOPENED-Excepti
onoccurswhenyouopenacursorwhi
chi
sal
readyopened.
NO_DATA_F
OUND-Excepti
onoccurswhenaSELECT…I
NTOcl
ausedoesn’
treturnanyrow f
roma
table.
TOO_MANY_ROWS-Excepti
onoccurswhenSELECTmorethanonerowi
navari
abl
eorrecord.
ZERO_DI
VIDE -Wheneverwedi vi
deanynumberbyzerotheoutputwoul
dbe‘ORA-01
476 di
visor
isequaltozero’
.Excepti
onoccurswhenyoutrytodivi
deanumberbyzero.
I
NVALI
D_NUMBER-Excepti
onoccurswhenyouconvertstri
ngtonumber.
VALUE_ERROR-Excepti
onoccurswhenconversi
onfail
s(i
.
e.varchartonumber)andi
ftheval
ue
islongerthanthedecl
aredlengthofthevari
able.
OTHERS-Thi
sisusedtotrapallremaini
ngexceptionsthathasnothandledbyabovefour
predefi
nedexcepti
onandcanhandleaboveexceptiontoo.
Thisexcepti
onmustbel astwhenyou
havemorethanonepredefi
nedexceptions.
2) User-Def
ined
Apartfromsystemexcepti
onyoucouldexpl
ici
tlydefi
neandrai
seexcepti
on.Theseareknown
asuser-def
inedexcepti
on.
Inuser-def
inedweuse‘RAI
SE’
keywordtoforci
blyraisean
excepti
on.
Rul
estobef
oll
owed
1
) Excepti
onmustbedecl
aredatthedecl
arati
onsecti
on.
2) Excepti
onshoul
dberai
sedi
nexecuti
onsecti
on.
3) Excepti
onshoul
dbehandl
edi
nexcepti
onsecti
on.
3) Non-Pre-Def
ined
Thesystemexcepti
onforwhichoracl
edoesn’thavenamesiscallednonpre-defi
nedor
unnamedsystemexcepti
on.Hereweuse‘PRAGMAEXCEPTI
ON_I
NIT’
isusedtobinduserdef
ined
excepti
ontoaparti
cularerrornumberor‘OTHERS’
.
RAI
SE_APPLI
CATI
ON_ERROR
Thi
sisusedtodi
spl
ayuserdef
inederrormessagewi
therrorumberrangi
ngf
rom-20000to-
20999.
Rul
esf
orwri
tingexcepti
on
1) Ifyouusemorethanoneexcepti
oni
nabl
ockthenonl
yoneexcepti
onf
iresthatwi
llbe
basedonfirsterroroccurrence.
2) I fyouuse‘OTHERS’
excepti
onwi
thanotherexcepti
onthen‘
OTHERS’
mustbel
asti
n
excepti
onsection.
CURSORS
CursorisaSQLpri
vateworkarea.Itopensanareaofmemorywherethequeryi sparsedand
executed.I
tstorestheresul
tofthequeryandmani pulatesi
ntemporaryworkarea.Acursor
canholdmorethan1rows,butitprocessrowbyrow. Thesetofrowsthecursorholdsiscal
led
theactiveset.
Cursorattri
butes:
1
) FOUND–Returnstruei
fanINSERT,
DELETE&UPDATEaffectoneormorerowsoraSELECT
I
NTOreturnsoneormorerows.Otherwiseitreturnsf
alse.
2) NOTF OUND–Iti
soppositeto‘F
OUND’
.Returnstruei
fanINSER,DELETE&UPDATEaf
fectedno
rowsoraSE
LECTINTOreturnednorows.Otherwisei
treturnsfalse.
3) ROWCOUNT–Returnsnumberofrowsaf
fectedbyI
NSERT,
DELETE&UPDATEorreturnedby
SELECTI
NTOstatements.
4) I
SOPEN–Returnstruei
fcursori
sopenedandi
tisf
alsehencursori
snotopened.
Typesofcursor:
1
) I
mpl
ici
tCursor
Theyarecreatedautomati
call
ywhenDMLstatementsl ikeINSERT,UPDATEandDELETE
statementsareexecutedandSELECTstatementthatreturnj ustonerowi sexecuted.
Exampl
e
BEGI
N
DELETEF
ROMT1
;
DBMS_OUTPUT.
PUT_LI
NE(
SQL%ROWCOUNT)
;
I
NSERTI
NTOT1VALUES(
1);
DBMS_OUTPUT.
PUT_LI
NE(
SQL%ROWCOUNT)
;
END;
Output:
-
Exampl
e
BEGI
N
DELETEF
ROMT1WHEREA=2;
I
FSQL%F
OUNDTHENDBMS_OUTPUT.
PUT_LI
NE(
'DELETESUCCEEDED'
);
I
NSERTI
NTOT1VALUES(
4);
DBMS_OUTPUT.
PUT_LI
NE(
SQL%ROWCOUNT)
;
ENDI
F;
END;
/
Output:
-
DELETESUCCEEDED
Exampl
e
BEGI
N
DELETEF
ROMT1WHEREA=5;
I
FSQL%NOTF
OUNDTHENDBMS_OUTPUT.
PUT_LI
NE(
'DELETEUNSUCESSF
UL'
);
I
NSERTI
NTOT1VALUES(
4);
DBMS_OUTPUT.
PUT_LI
NE(
SQL%ROWCOUNT)
;
ENDI
F;
END;
Output:
-
DELETEUNSUCESSF
UL
2) Expl
ici
tCursor
Theseshoul
dbedeclaredexpl
ici
tlybyuserwhen‘SELECT’
keywordreturnsmorethan1rowsor
norows.Thoughi
tstoresmultipl
erows,onlyonerowcanbeprocessedatatimewhichis
call
edcurrentrow.
Exampl
e
DECLARE
I
EMPLOYEES.
FI
RST_NAME%TYPE;
JE
MPL
OYEES.
SALARY%TYPE;
CURSORC1I
SSE
LECTF
IRST_NAME,
SALARYF
ROMEMPL
OYEESWHEREDEPARTMENT_I
D=60;
BEGI
N
OPENC1
;
LOOP
F
ETCHC1I
NTOI
,
J;
DBMS_OUTPUT.
PUT_LI
NE(
I|
|'
'|
|J
);
EXI
TWHENC1
%FOUND;
ENDLOOP;
CLOSEC1
;
END;
Output:
-
Al
exander9000
SELECTf
orUPD
ATE
Exampl
e
DECLARE
CURSORC1I
SSE
LECTAF
ROMT1F
ORUPDATEOFANOWA
IT;
BEGI
N
OPENC1
;
UPDATET1SETA=5WHEREA=6;
CLOSEC1
;
COMMI
T;
END;
Output:
-
PL/
SQLproceduresuccessf
ull
ycompl
eted.
WHERECURRENTOF
Thisi
susedwhenyouupdateordel eterowsusingcursor.
Thisall
owsyoutoupdateordelete
therowcurrentlybei
ngaddressed,withoutcreati
ngreferencetoROWI
D.Whenyouusethis
thenthecursormustcontai
nF ORUPDATEclause.
Exampl
e
DECLARE
I
T1.
A%TYPE;
CURSORC1I
SSE
LECTAF
ROMT1WHEREA=4F
ORUPDATEOFA;
BEGI
N
OPENC1
;
F
ETCHC1I
NTOI
;
I
FC1
%NOTF
OUNDTHEN
DBMS_OUTPUT.
PUT_LI
NE(
'NOROWSF
OUND'
);
ELSE
UPDATET1SETA=9WHERECURRENTOFC1
;
COMMI
T;
ENDI
F;
CLOSEC1
;
END;
Output:
-
PL/
SQLproceduresuccessf
ull
ycompl
eted.
Exampl
e
DECLARE
I
T1.
A%TYPE;
CURSORC1I
SSE
LECTAF
ROMT1WHEREA=9F
ORUPDATEOFA;
BEGI
N
OPENC1
;
F
ETCHC1I
NTOI
;
I
FC1
%NOTF
OUNDTHEN
DBMS_OUTPUT.
PUT_LI
NE(
'DATANOTF
OUND'
);
ELSE
DELETEF
ROMT1WHERECURRENTOFC1
;
ENDI
F;
CLOSEC1
;
END;
Output:
-
PL/
SQLproceduresuccessf
ull
ycompl
eted.
CURSORWI
THPARAMETER
Exampl
e
DECLARE
AE
MPLOYEES.
FI
RST_NAME%TYPE;
CURSOREMP_CU
RSOR
(
AEMPLOYEES.
DEPARTMENT_I
D%TYPE)I
S
SELECTF
IRST_NAMEF
ROMEMPLOYEESWHEREDEPARTMENT_I
D=A;
BEGI
N
OPENEMP_CURS
OR(
60)
;
LOOP
F
ETCHEMP_C
URSORI
NTOA;
DBMS_OUTPUT.
PUT_LI
NE(
A);
EXI
TWHENEMP_CURSOR%N
OTF
OUND;
ENDLOOP;
CLOSEEMP_CUR
SOR;
OPENEMP_CURS
OR(
20)
;
LOOP
F
ETCHEMP_C
URSORI
NTOA;
DBMS_OUTPUT.
PUT_LI
NE(
A);
EXI
TWHENEMP_CURSOR%N
OTF
OUND;
ENDLOOP;
CLOSEEMP_CUR
SOR;
END;
Output:
-
Al
exander
Bruce
Davi
d
Val
li
Di
ana
Di
ana
Mi
chael
Pat
Pat
Whentousecursor
1
) I
fyouwanttoprocessrowbyrowthenusecursor.
Di
sadvantageofcursor
1
) Perf
ormancedropsdown.
REFCURSOR:
I
tisadatatype.
Itwi
llcl
osei
mpl
ici
tly.
Therearetwotypesofrefcursor
a) Weakrefcursor
Queryresul
twi
llbestored.
Exampl
e
CREATEORREPLACEPROCED
UREP1
(II
NNUMBER,
OOUTSYS_REF
CURSOR)
AS
BEGI
N
OPENOF
OR
SELECTF
IRST_NAME,
SALARYF
ROMEMPLOYEESWHEREEMPLOYEE_I
D=I
;
END;
/
VARI
ABLEOREF
CURSOR;
EXECP1
(90,
:
O);
b) Strongref
-cursor
I
treturnsaval
uewhi
chcanbeofanydatatype.
Exampl
e
CREATEORREPLACEPACKAG
EPKG1AS
TYPETNAMEI
SREFCURSORRETURNDEPARTMENTS%ROWTYPE;
ENDPKG1
;
STOREDPROCEDURE
I
tisanamedPL/ SQLsubprograms.I
tiscompiledandstoredi ndatabaseforrepeatedexecuti
on.
I
tcanacceptanargumentandcanreturnaval ue.Procedureperformsanaction.I
tisaschema
object.
Itimprovestheperformanceofanapplicationbyreducingnetworktraffic.
Itcan
acceptparameter.I
fprocedureiscreatedoutsidethepackagetheni ti
scalledasstoredor
standal
onesubprogramsandi fi
screatedinpackagetheni tiscal
ledpackagedsubprogram.
• Wecancreateprocedurei
nsi
deanonymousbl
ock.
• Wecancreateprocedurei
nsi
depackage.
• Wecancreateprocedurei
nsi
deprocedure.
Exampl
e
CREATEPROCEDUREP1AS
KE
MPLOYEES.
FI
RST_NAME%TYPE;
LE
MPLOYEES.
SALARY%TYP
E;
BEGI
N
SELECTF
IRST_NAME,
SALARY
I
NTOK,
L
F
ROMEMPLOYEESWHEREEMPLOYEE_I
D=1
00;
DBMS_OUTPUT.
PUT_LI
NE(
K||
''
|
|L)
;
END;
Toal
terprocedure:
Exampl
e
CREATEORREPLACEPROCED
UREP1AS
KE
MPLOYEES.
FI
RST_NAME%TYPE;
LE
MPLOYEES.
SALARY%TYP
E;
BEGI
N
SELECTF
IRST_NAME,
SALARY
I
NTOK,
L
F
ROMEMPLOYEESWHEREEMPLOYEE_I
D=1
00;
DBMS_OUTPUT.
PUT_LI
NE(
K||
''
|
|L)
;
END;
Toexecuteprocedure:
SQLPLUS
EXECP1
;
i
SQL
PLUS
BEGI
N
P1
;
END;
Todropprocedure:
DROPPROCEDUREP1
;
Todescri
beprocedure:
Exampl
e
DESCRI
BEP2;
Tovi
ewenti
requeryofanstoredprocedure
Exampl
e
SELECTTEXTF
ROMUSER_SOURCEWHERENAME='
P2'
;
I
saposi
tionalparameter.
LocalProcedure:
Wheneveryoucreateprocedurei
nsi
deanonymousblockiscal
ledlocalprocedure.Thi
s
proceduredoesn’
tstorei
ndatabaseandcannotbecall
edoutsideanonymousbl ock.
Exampl
e
DECLARE
PROCEDUREP2
AS
AE
MPLOYEES.
FI
RST_NAME%TYPE;
BEGI
N
SELECTF
IRST_NAME
I
NTOA
F
ROMEMPLOYEESWHEREEMPLOYEE_I
D=1
00;
DBMS_OUTPUT.
PUT_LI
NE(
A);
END;
BEGI
N
I
NSERTI
NTOT1VALUES(
3,'
SHELL'
);
COMMI
T;
P2;
I
NSERTI
NTOT1VALUES(
1,
'ORACLE'
);
ROLLBACK;
END;
Parametertypes:
I
N:
Thi
sindi
catesthatval
uesmustbesuppl
iedwhenyouexecutetheprocedure.
Exampl
e
CREATEORREPLACEPROCED
UREP2(AI
NNUMBER)
AS
BE
MPLOYEES.
FI
RST_NAME%TYPE;
BEGI
N
SELECTF
IRST_NAME
I
NTOB
F
ROMEMPLOYEESWHEREEMPLOYEE_I
D=A;
DBMS_OUTPUT.
PUT_LI
NE(
B);
END;
Output
Steven
OUT:
Exampl
e
VARI
ABLEBNUMBER;
CREATEORREPLACEPROCED
UREP1(
AINNUMBER,
BOUTNUMBER)
AS
BEGI
N
DBMS_OUTPUT.
PUT_LI
NE(
A);
END;
EXECP1
(10,
:
B);
Output
1
0
I
N/OUT:
Exampl
e
VARI
ABLEBNUMBER;
EXEC:
B:
=10;
CREATEORREPLACEPROCED
UREP1(
CINOUTNUMBER)
AS
BEGI
N
DBMS_OUTPUT.
PUT_LI
NE(
C);
END;
EXECP1
(:
B);
Output
1
0
F
UNCTI
ONS:
I
tisanamedPL/SQLprogramwhichcanbecal
ledasstoredf
uncti
on.
Iti
scompi
ledandstoredi
n
databasef
orrepeatedexecuti
on.
I
tcanacceptargumentsandmustreturnaval ue.
Youcanhavemulti
plereturnstatements
butonlyonewillbeexecuted.
Wecancreatef
unctionatcli
ent-si
deappli
cationusi
ng
procedurebui
lder.
F
uncti
oncomputesaval
ue.
F
uncti
oncanbecal
ledaspartofanexecuti
on.
F
uncti
oncannotperf
ormDML.
F
uncti
oncanreturnonl
yoneval
ue.
F
uncti
oncanuseonl
yparameterI
N
I
tisaschemaobj
ect
• Wecancreatef
uncti
oni
nsi
depackage.
• Wecancreatef
uncti
oni
nsi
deanonymousbl
ock.
• Wecancreatef
uncti
oni
nsi
deprocedure.
I
ff uncti
oni
screatedoutsi
dethepackagetheni
tiscal
ledasstoredorstandal
onesub
programsandi
fitcreatedi
nsi
depackagetheniti
scall
edpackagedsubprograms.
Exampl
e
Tocreatef
uncti
ons
CREATEF
UNCTI
ONF
1(AI
NNU
MBER)
RETURNVARCHAR2
AS
BE
MPLOYEES.
FI
RST_NAME%TYPE;
BEGI
N
SELECTF
IRST_NAME
I
NTOB
F
ROMEMPLOYEESWHEREEMPLOYEE_I
D=1
00;
DBMS_OUTPUT.
PUT_LI
NE(
B);
RETURNB;
END;
Toal
terf
uncti
on
CREATEORREPLACEF
UNCTI
ONF
1(AI
NNUMBER)
RETURNVARCHAR2
AS
BE
MPLOYEES.
FI
RST_NAME%TYPE;
BEGI
N
SELECTF
IRST_NAME
I
NTOB
F
ROMEMPLOYEESWHEREEMPLOYEE_I
D=1
00;
DBMS_OUTPUT.
PUT_LI
NE(
B);
RETURNB;
END;
Todropf
uncti
on
DROPF
UNCTI
ONF
1;
Toexecuteaf
uncti
on
SELECTF
1(1
00)F
ROMDUAL;
Tovi
ewcol
umnsi
nfuncti
on
DESCRI
BEF
1;
Tovi
ewenti
recodi
ngofanf
uncti
on
SELECTTEXTF
ROMUSER_SOURCEWHERENAME='
F1'
;
Parameter
I
N
Exampl
e
CREATEORREPLACEF
UNCTI
ONF
1(AI
NNUMBER)
RETURNVARCHAR2
AS
BE
MPLOYEES.
FI
RST_NAME%TYPE;
BEGI
N
SELECTF
IRST_NAME
I
NTOB
F
ROMEMPLOYEESWHEREEMPLOYEE_I
D=1
00;
DBMS_OUTPUT.
PUT_LI
NE(
B);
RETURNB;
END;
Output
steven
Recursi
vef
uncti
on
Whenasubprogramcal
lsi
tsel
fisref
ereedasrecursi
vecal
landtheprocessi
sknownas
recursi
on.
Exampl
e
DECLARE
F
IRSTVARCHA
R2(
40)
;
F
UNCTI
ONF
1(ANUMBER)
RETURNVARCHAR2
AS
BE
MPLOYEES.
FI
RST_NAME%TYPE;
BEGI
N
SELECTF
IRST_NAME
I
NTOB
F
ROMEMPLOYEESWHEREEMPLOYEE_I
D=1
00;
DBMS_OUTPUT.
PUT_LI
NE(
B);
RETURNB;
ENDF
1;
BEGI
N
F
IRST:
=F1
(10)
;
DBMS_OUTPUT.
PUT_LI
NE(
'NAME'
|
|FI
RST)
;
END;
Output
steven
NAMEsteven
I
nvoki
ngf
uncti
oni
nSQLStatement
Exampl
e
CREATEORREPLACEF
UNCTI
ONF
2(P_VALUEI
NNUMBER)
RETURNNUMBERI
S
BEGI
N
RETURN(
P_VAL
UE*0.
08)
;
ENDF
2;
Output:
SELECTF
IRST_NAME,
LAST_NAME,
SALARY,
F2(
SALARY)
F
ROM
EMPLOYEESWHEREDEPARTMENT_I
D=1
00;
F
IRST_NAME LAST_NAME SALARY F
2(SALARY)
Nancy Greenberg 1
2000 960
Dani
el F
avi
et 9000 720
J
ohn Chen 8200 656
I
smael Sci
arra 7700 61
6
Di
fferencebetweenStoredProcedureandF
ucti
ons:
1
.) Procedureperf
ormanacti
onandF
uncti
onsperf
ormcomputeval
ues.
2.
) Procedurecanacceptandcanreturnaval
ue.
But,
functi
onscanacceptaval
ueandmust
returnaval
ue.
3.
) F
uncti
onscanbecal
lfromSQLStatements,
proceduresnot.
4.
) F uncti
onsaregenerall
yrestri
ctedtoreturni
ngasi
ngl
eval
ue,
whi
leprocedurescan
havemulti
pleOUTparameters.
5.
) Therearesi tuationswherefunctionsaremoreusef ulinqueries(i.
e.youwanttocreate
yourownfunctionthatcanbeusedinaqueryl ikethestandardf unctionsUPPER,
etc.
).I
nsome
cli
ent-si
delanguages,i
t'ssl
ightl
yeasiertocal lstoredproceduresratherthanstored
functi
ons.
TRI
GGE
R:
TriggerisanamesPL/ SQLbl
ockthatisstoredindatabaseandinvokedrepeatedly.
It
automati call
yfireswhenaneventoccursinschema,tablesordatabase.Youcanenabl
eand
di
sabl etrigger.
Tri
ggeri
susedf
or
• Preventi
nval
idtransacti
on
• Tabl
emodi
ficati
on
• Compl
exbusi
nessrul
e.
Restri
cti
ons
• WecannotuseCOMMI
T,SAVEPOI
NT&ROLLBACKi
ntri
gger.
• WecannotuseDDLi
ntri
ggerbecausetheyhavei
mpl
ici
tcommi
t.
Exampl
e
Tocreatetri
gger:
CREATETRI
GGE
RTRG_T1
BEF
OREI
NSERTORUPDATEORDELETEONT1
F
OREACHROW
BEGI
N
I
NSERTI
NTOT2VALUES(
1);
END;
ToupdateTri
gger:
CREATEORREPLACETRI
GGERTRG_T1
BEF
OREI
NSERTORUPDATEORDELETEONT1
BEGI
N
I
NSERTI
NTOT2VALUES(
1);
END;
Todroptri
gger:
DROPTRI
GGERTRG_T1
;
Toenabl
eaparti
cul
artri
gger:
ALTERTRI
GGE
RTRG_T1ENABLE;
Toenabl
eal
ltri
ggersf
orantabl
e:
ALTERTABLET1ENABLEALLTRI
GGERS;
Todi
sabl
eaparti
cul
artri
gger:
ALTERTRI
GGE
RTRG_T1DI
SABLE;
Todi
sabl
eal
ltri
ggersf
orantabl
e:
ALTERTABLET1DI
SABLEALLTRI
GGERS;
Tovi
ewtri
ggerquery:
SELECTTEXTF
ROMUSER_SOURCEWHERENAME='
TRG_T1
';
Tri
ggerTypes:
1
.) StatementLevelTri
gger(
or)Tabl
eLevelTri
gger
I
tfiresonl
yonceforeachevent.Thi
sisadef
aul
ttri
gger.
Itf
iresonceeveni
fnorowsare
aff
ectedbythetriggeri
ngevent.
Exampl
e
Bef
oreTri
gger:
CREATEORREPLACETRI
GGERTRG_T1
BEF
OREI
NSERTORUPDATEORDELETEONT1
BEGI
N
I
NSERTI
NTOT2VALUES(
1);
END;
Af
terTri
gger:
CREATEORREPLACETRI
GGERTRG_T1
AF
TERI
NSERTORUPDATEORDELETEONT1
BEGI
N
I
NSERTI
NTOT2VALUES(
1);
END;
I
nsteadOf
:
CREATETRI
GGE
RTRG_T1
I
NSTEA
DOFI
NSERTORUPDATEORDELETEONV1
BEGI
N
I
NSERTI
NTOT2VALUES(
1);
END;
2.
) RowLevelTri
gger:
I
tf i
resonceforeachrowaffectedbythetri
ggeri
ngevent.
Thi
stri
ggerwi
llnotf
irewhenno
rowsareaffectedbytri
ggeringevent.
Exampl
e
Bef
oreTri
gger:
CREATETRI
GGE
RTRG_T1
BEF
OREI
NSERTORUPDATEORDELETEONT1
F
OREACHROW
BEGI
N
I
NSERTI
NTOT2VALUES(
1);
END;
Af
terTri
gger:
CREATETRI
GGE
RTRG_T1
AF
TERI
NSERTORUPDATEORDELETEONT1
F
OREACHROW
BEGI
N
I
NSERTI
NTOT2VALUES(
1);
END;
I
nsteadOf
:
CREATETRI
GGE
RTRG_T1
I
NSTEA
DOFI
NSERTORUPDATEORDELETEONV1
F
OREACHROW
BEGI
N
I
NSERTI
NTOT2VALUES(
1);
END;
1
) DMLTri
ggers
DMLTriggersi
screatedonei
thertabl
eorviewandtri
ggeri
ngeventcomposingofI
nsert,
Update&Delete.
Tocreatetri
ggeronmergestatement,
createtri
ggeronInsert&update
statementtowhi
chthemergeoperati
ondecomposes.
2) SystemTri
gger
I
fatriggeriscreatedonSchemaordatabasethenthetri
ggeri
ngeveni
scomposedofdata
def
ini
tionlanguageordatabaseoperati
ons.
a) Schematri
ggers
I
tincl
udesDDLstatementsCREATE,
ALTERandDRO
P.
Exampl
e
CREATEORREPLACETRI
GGERTRG_T1
BEF
OREDROPONHR.
SCHEMA
BEGI
N
I
NSERTI
NTOT1VALUES(
1);
END;
b) I
nsteadofCreateTri
gger
Exampl
e
CREATETRI
GGE
RTRG_T1
I
NSTEA
DOFCREATEONSCHEMA
BEGI
N
I
NSERTI
NTOT1VALUES(
1);
END;
c) DatabaseTri
gger
I
tincl
udesdatabasestartupandshutdown.
Exampl
e
CREATETRI
GGE
RTRG_T1
AF
TERLOGONONDATABASE
BEGI
N
I
NSERTI
NTOT2VALUES(
1);
END;
CREATETRI
GGE
RTRG_T2
BEF
ORELOGOF
FONDATABAS
E
BEGI
N
I
NSERTI
NTOT2VALUES(
2);
END;
3) Condi
tionalTri
ggers
I
nthisweuse‘
WHEN’cl
ausewhichspeci
fiesanSQLcondi
tionandthateval
uatedf
oreachrow.
Whenyouuse‘
WHEN’
clausethenyoumustdefini
telyuse‘
F OREACHROW’
.
Tri
ggerTi
mings:
1
) BEF
ORE–Tri
ggerf
iresf
irstandtheneventf
ires.
2) AF
TER–Eventf
iresf
irstandthentri
ggersf
ires.
3) I NSTEADOF–thisi
susewhenyoucreatetri
ggeronvi
ew.
Thi
sstopsi
nserti
ng,
del
eti
ng
andupdatingaview.
Tri
ggerEvents:
DataMani
pul
ati
onLanguage(
Insert,
Update&Del
ete)
DataDef
ini
tionLanguage(
Drop,
Create,
Truncate,
Rename)
Logon,
Logof
f
PACKAGES:
Packagegroupsl
ogical
lyrelatedsub-programs(
procedureandf
uncti
oni
scal
ledsubprogram)
.
Iti
sanschemaobj ect.
Itconsistsof2parts
1
) Packagespeci
ficati
on
I
tcontainsdeclarati
on.Youcandecl
arecursor,
type,
variabl
es,subprograms,excepti
onsand
constant.
Youcancreatepackagespecif
icati
onwithpackagebody.Whateverdeclaredi
n
packagespeci
ficati
onisglobal
.
2) Packagebody
I
tcontai nsdefi
niti
on.I
tcontainsthedefiniti
onforsubprogramsthatisl
istedi
npackage
speci
ficationanditcontai
nslocalprocedureandonetimeprocedure.
Youcandeletepackage
bodywithoutdeletingpackagespecifi
cation.
I
tcannotbei
nvoked,
parameteri
zedornested.
Advantage:
1
. I
tal
loworacl
eservertoreadmul
tipl
eobj
ecti
ntomemoryatonce.
2. Overl
oadi
ng–mul
tipl
esubprogramsatsameti
me.
3. Userscandecl
aregl
obalvari
abl
es,
cursors&user-def
inedexcepti
on.
4. Wecanuse‘ PRAGMASERI
ALLY_REUSABLE’
tode-al
locatememoryaftereachcall
.I
fyouare
usi
ngthisyouneedtousebothinpackagebody&packagespeci
ficati
onbef
oredefini
tionor
decl
aration.
Exampl
e
CREATEORREPLACEPACKAG
EPKG2AS
--DECLARTI
ON
--GLOBALVARI
ABLE
OTPVARCHAR2(
50)
;
F
NAMEEMPLOYEES.
FI
RST_NAME%TYPE;
EI
DEMPLOYEES.
EMPLOYEE_I
D%TYPE;
SALEMPLOYEES.
SALARY%TYPE;
--GLOBALVARI
ABLE
--SUBPROGRAMS
PROCEDUREP1
(EI
DINEMPLOYEES.
EMPLOYEE_I
D%TYPE)
;
PROCEDUREP2(
FNAMEI
NEMPLOYEES.
FI
RST_NAME%TYPE,
LNAMEI
NEMPLOYEES.
LAST_NAME%TYPE)
;
PROCEDUREP2(
FNAMEEI
NEMPLOYEES.
FI
RST_NAME%TYPE,
LNAMEEI
NEMPLOYEES.
LAST_NAME%TYPE)
;
PROCEDUREP2(FNAMEINEMPLOYEES.
FI
RST_NAME%TYPE,
LNAMEI
NEMPLOYEES.
LAST_NAME%TYPE,
EIDI
N
EMPLOYEES.EMPLOYEE_I
D%TYPE);
F
UNCTI
ONF
1(EI
DINEMPLOYEES.
EMPLOYEE_I
D%TYPE)RETURNNUMBER;
F
UNCTI
ONTAX
(TAXRATEI
NNUMBER)RETURNNUMBER;
PROCEDUREAWR_BONUS(
AINNUMBER,
BINNUMBER)
;
--SUBPROGRAMS
--DECLARTI
ON
ENDPKG2;
CREATEORREPLACEPACKAG
EBODYPKG2AS
--DEF
INI
TION
--LOCALPROCEDURE
PROCEDUREP3(
AINNUMBER,
BINNUMBER,
CINNUMBER)
AS
BEGI
N
DBMS_OUTPUT.
PUT_LI
NE(
A+B+C)
;
ENDP3;
--LOCALPROCEDURE
--USERDEF
INEDPACKAGE
F
UNCTI
ONTAX
(TAXRATEI
NNUMBER)
RETURNNUMBER
AS
TAXPERNUMBER:
=0.
08;
BEGI
N
RETURN(
TAXRATE*
TAXPER)
;
ENDTAX;
--USERDEF
INEDPACKAGE
PROCEDUREP1
(EI
DINEMPLOYEES.
EMPLOYEE_I
D%TYPE)
AS
BEGI
N
SELECTF
IRST_NAMEI
NTOF
NAMEF
ROMEMPLOYEESWHEREEMPLOYEE_I
D=EI
D;
DBMS_OUTPUT.
PUT_LI
NE(
FNAME
);
ENDP1
;
PROCEDUREP2(
FNAMEI
NEMPLOYEES.
FI
RST_NAME%TYPE,
LNAMEI
NEMPLOYEES.
LAST_NAME%TYPE)
AS
BEGI
N
SELECTEMPLOYEE_I
DINTOEI
DFROMEMPLOYEESWHE
REF
IRST_NAME=F
NAMEANDLAST_NAME=LNAME;
P3(
2,3,
5);
DBMS_OUTPUT.
PUT_LI
NE(
'1
'|
|'
'|
|FNAME|
|'
-'|
|LNAME|
|'
-'|
|EI
D);
ENDP2;
PROCEDUREP2(
FNAMEEI
NEMPLOYEES.
FI
RST_NAME%TYPE,
LNAMEEI
NEMPLOYEES.
LAST_NAME%TYPE)
AS
BEGI
N
SELECTEMPLOYEE_I
DINTOEI
DFROMEMPLOYEESWHE
REF
IRST_NAME=F
NAMEEANDLAST_NAME=LNAMEE;
DBMS_OUTPUT.
PUT_LI
NE(
'2'
||
''|
|
FNAMEE|
|'
-'|
|LNAMEE|
|'
-'|
|EI
D);
ENDP2;
PROCEDUREP2(FNAMEINEMPLOYEES.
FI
RST_NAME%TYPE,
LNAMEI
NEMPLOYEES.
LAST_NAME%TYPE,
EIDI
N
EMPLOYEES.EMPLOYEE_I
D%TYPE)
AS
BEGI
N
SELECTSALARYINTOSALF
ROMEMPLOYEESWHEREF
IRST_NAME=F
NAMEANDLAST_NAME=LNAMEAND
EMPLOYEE_ID=EI
D;
DBMS_OUTPUT.
PUT_LI
NE(
FNAME|
|'
-'|
|LNAME|
|'
-'|
|SAL)
;
ENDP2;
F
UNCTI
ONF
1(EI
DINEMPLOYEES.
EMPLOYEE_I
D%TYPE)
RETURNNUMBER
AS
SALEMPLOYEES.
SALARY%TYPE;
BEGI
N
SELECTSALARYI
NTOSALF
ROMEMPLOYEESWHEREEMPLOYEE_I
D=EI
D;
RETURNSAL;
ENDF
1;
--F
ORWARDDECLARTAI
ON
PROCEDURECAL_RATE(
AINNUMBER,
BINNUMBER)
;
--F
ORWARDDECLARTAI
ON
PROCEDUREAWR_BONUS(
AINNUMBER,
BINNUMBER)
I
S
BEGI
N
CAL_RATE(
A,B)
;
ENDAWR_BONUS
;
PROCEDURECAL_RATE(
AINNUMBER,
BINNUMBER)
I
S
BEGI
N
DBMS_OUTPUT.
PUT_LI
NE(
A+B)
;
ENDCAL_RATE;
--ONETI
MEONLYPROCEDURE
BEGI
N
SELECTF
IRST_NAMEI
NTOOTPF
ROMEMPLOYEESWHER
EEMPLOYEE_I
D=OTP;
DBMS_OUTPUT.
PUT_LI
NE(
OTP)
;
--ONETI
MEONLYPROCEDURE
--DEF
INI
TION
ENDPKG2;
Exampl
e
Toexecuteproceduref
rompackage
EXECPKG2.
P2(
'Steven'
,
'Ki
ng'
,
100)
;
Toexecutef
uncti
onf
rompackage
SELECTPKG2.
F1(
100)F
ROMDUAL;
Toexecuteuserdef
inedpackage
SELECTPKG2.
TAX(
SALARY)
,SALARYF
ROMEMPLOYEES;
Todroppackage:
DROPPACKAGEPKG3;
Todroppackagebody:
DROPPACKAGEBODYPKG3;
Oneti
meonl
yprocedure:
I
tisexecutedonl
yonceinthecurrentsessi
on.
Youcan’
tuse‘
END’
inoneti
meonl
yprocedure.
Thi
sshouldbedefi
nedl
astinpackagebody.
Exampl
e
Toexecuteoneti
meonl
yprocedure
DECLARE
NAMEVARCHAR2(
50)
;
BEGI
N
NAME:
=PKG2.
OTP;
DBMS_OUTPUT.
PUT_LI
NE(
NAME)
;
END;
/
Bodi
lesspackage:
Youcanusebodi
lesspackagef
orexecuti
on.
Herethesevari
abl
esexi
stonl
yinthi
ssessi
on.
Exampl
e
CREATEORREPLACEPACKAG
EPKG3AS
NUM1CONSTANTNUMBER:
=10;
NUM2CONSTANTNUMBER:
=11
;
NUM3CONSTANTNUMBER:
=12;
NUM4CONSTANTNUMBER:
=13;
ENDPKG3;
EXECUTEDBMS_OUTPUT.
PUT_LI
NE(
'RESULT'
|
|'
='
||
20*
PKG3.
NUM3)
;
Output
240
F
orwardDecl
arati
on:
Whenthesubprogramsaredef
inedi
nal
phabeti
calorderandyoucannotcal
lprocedure
CAL_RATE’
from‘
AWR_BONUS’
.
Sobef
orecal
li
ngprocedure‘
CAL_RATE’
wemustdef
inei
t.
PRAGMA
I
tref
erstocompi
lerdi
recti
vewhi
chi
susedtoprovi
dei
nformati
ontothecompi
ler.
PRAGMAAUTONOMI
OUS_TRANSACTI
ON
I
tperf ormsindependenttransactionbetweenbegi
nandendwi
thoutaf
fecti
ngenti
re
transactionorothertransaction.
Youmustuse‘COMMIT’or‘
ROLLBACK’el
sewegetanerror‘
ORA-0651
9acti
veautonomous
transacti
ondetectedandrollback.
Exampl
e
DECLARE
PROCEDUREP1
AS
PRAGMAAUTONOMOUS_TRANSACTI
ON;
BEGI
N
I
NSERTI
NTOT1VALUES(
2);
COMMI
T;
END;
BEGI
N
I
NSERTI
NTOT1VALUES(
1);
P1
;
I
NSERTI
NTOT1VALUES(
3);
ROLLBACK;
END;
PRAGMAEXCEPTI
ON_I
NIT:
I
tisusedinexcepti
on.I
tisusedtohandl
etheerrorf
orwhi
chweknowtheerrornumberi
s
cal
lednon-pre-defi
nedexcepti
on.
Exampl
e
DECLARE
GREENSEXCEPTI
ON;
PRAGMAEXCEPTI
ON_I
NIT(
GREENS,
-01
476)
;
BEGI
N
DBMS_OUTPUT.
PUT_LI
NE(
1/0)
;
DBMS_OUTPUT.
PUT_LI
NE(
'PRI
NT1
')
;
EXCEPTI
ON
WHENGREENSTHEN
DBMS_OUTPUT.
PUT_LI
NE(
'PRI
NT2'
);
END;
Output:
-
PRI
NT2
PRAGMASERI
ALLY_REUSABLE:
I
tisusedtousepackagef
orsi
ngl
ecalltotheserverafterthecal
lismadethenpackagei
s
rel
easedfrommemorytorecl
aiminanothercal
ltoserver.
Exampl
e
CREATEORREPLACEPACKAG
EPKG1I
S
PRAGMASERI
ALLY_REUSABLE;
NUMNUMBER:
=0;
PROCEDUREENTER(
NNUMBER)
;
PROCEDURESHOW;
ENDPKG1
;
CREATEORREPLACEPACKAG
EBODYPKG1I
S
PRAGMASERI
ALLY_REUSABLE;
PROCEDUREENTER(
NNUMBER)I
S
BEGI
N
PKG1
.NUM:
=N;
END;
PROCEDURESHOWI
S
BEGI
N
DBMS_OUTPUT.
PUT_LI
NE(
'Num:
'|
|PKG1
.NUM)
;
END;
ENDPKG1
;
/
EXECUTEI
MMEDI
ATE
Thi
scommandi
susedf
orexecuti
ngdynami
cSQLstatementsanddatadef
ini
tionl
anguage
commands.
Exampl
e
BEGI
N
EXECUTEI
MMEDI
ATE'
TRUNCATETABLET1
';
END;
Dynami
cSQL:
Dynami
cSQLi
saSQLstatementthati
sconstructedandexecutedatprogramexecuti
onti
me.
Exampl
e
DECLARE
I
VARCHAR2(
20):
='B1
';
JN
UMB
ER;
BEGI
N
EXECUTEI
MMEDI
ATE'
SELECTCOUNT(
*)F
ROM'
||
IINTOJ
;
DBMS_OUTPUT.
PUT_LI
NE(
J);
END;
Output
DBMS_SQL:
I
tissimilarto‘
EXECUTEIMMEDIATE’
torundynamicSQLandDMLstatements.I
fthisisrunningi
n
anonymousblockthenitchecksforpri
vil
egeofthecurrentuserandi
fitisrunninginstored
proceduretheni
tchecksf orownerofthestoredprocedure.
Exampl
e
CREATEORREPLACEPROCED
UREDELETE_ALL(
NAMEI
NVARCHAR2,
ROWS_DELETEOUTNUMBER)
I
S
CURSOR_NAMEI
NTEGER;
BEGI
N
CURSOR_NAME:
=DBMS_SQL.
OPEN_CURSOR;
DBMS_SQL.
PARSE(
CURSOR_NAME,
'
DROPTABLE'
|
|NAME,
DBMS_SQL.
NATI
VE)
;
ROWS_DELETE:
=DBMS_SQL.
EXECUTE(
CURSOR_NAME)
;
DBMS_SQL.
CLOSE_CURSOR(
CURSOR_NAME)
;
END;
VARI
ABLEDELETEDNUMBER
EXECDELETE_ALL(
‘STUDENT’
,
:DELETED)
;
PRI
NTDELETE
D;
DBMS_J
OBS
Iti
saschedulePL/
SQLprogramtorun.I
tisveryusef
uli
nrunni
ngbatchj
obsduri
ngnopeak
hoursortorunmaintenanceduri
ngti
mesoflowusage.
Exampl
e
VARI
ABLEJNU
MBER
BEGI
N
DBMS_J
OB.
SUBMI
T(
J
OB=>:
J,
WHAT=>'
P1;
'
,
NEXT_DATE=>TRUNC(
SYSDATE)
,
I
NTERV
AL=>'
SYSDATE+1
/1440'
)
;
COMMI
T;
END;
Parameteri
nJobs
J
OB–Uni
quel
yidenti
fiesthej
oborj
obname.
WHAT–PL/
SQLcodetoexecuteasaj
ob.
NEXT_DATE–Nextexecuti
ondateofthej
ob.
I
NTERV
AL–Speci
fiesi
nwhi
chi
ntervali
tshoul
drun.
Toenabl
ejobs
BEGI
N
DBMS_J
OB.
BROK
EN(
121
,F
ALSE)
;
END;
Todi
sabl
ejobs
BEGI
N
DBMS_J
OB.
BROK
EN(
121
,TRUE)
;
END;
Tof
orcej
obs
BEGI
N
DBMS_J
OB.
RUN(
122)
;
END;
Toremovej
obs
BEGI
N
DBMS_J
OB.
REMOVE(
121
);
END;
Tol
istoutthej
obspresenti
nthedatabase
SELECT*F
ROMUSER_J
OBS;
DBMS_DDL
Thisi
susedtoaccesssomeSQLDDLstatementsf romstoredprocedure.Thi
spackageallows
devel
opertoaccesstoALTERandANALYZESQLstatementsthroughPL/ SQLenvi
ronment. Youcan
recompi
leprocedure,functi
on,package,
packagebodyortriggerusingDBMS_DDL.
ALTER_COMPILE
andyoucananalyzetable,cl
usterorindexusingDBMS_DDL.
ANALYZE_OBJ
ECT.
DBMS_OUTPUT
I
tisusedtodi
spl
ayoutputf
romPL/
SQLbl
ocks.
PUT
I
tstoresorappendstheoutputf
romprocedurei
ntheoutputbuf
fer.
Exampl
e
DECLARE
AN
UMBER;
BEGI
N
A:
=10;
DBMS_OUTPUT.
PUT(
A);
DBMS_OUTPUT.
PUT_LI
NE(
A);
END;
Output
1
010
NEW_LI
NE
I
thel
pstopri
nttheoutputi
nthenewl
ine.
Exampl
e
DECLARE
AN
UMBER;
BEGI
N
A:
=10;
DBMS_OUTPUT.
PUT(
A);
DBMS_OUTPUT.
NEW_LI
NE(
);
DBMS_OUTPUT.
PUT_LI
NE(
A);
END;
Output
1
0
1
0
PUT_LI
NE
I
tisacombi
nati
onofPUT&NEW_LI
NE
Exampl
e
DECLARE
AN
UMBER;
BEGI
N
A:
=10;
DBMS_OUTPUT.
PUT_LI
NE(
A);
END;
Output
1
0
GET_LI
NE
I
tconsi
stsoftwoargumentsi
ftherei
snol
inei
nbuf
fertheni
tisstatuswi
llbe1el
se0.
Exampl
e
DECLARE
AN
UMBER;
BN
UMBER:
=0;
BEGI
N
A:
=10;
DBMS_OUTPUT.
PUT(
A);
DBMS_OUTPUT.
GET_LI
NE(
A,B)
;
I
FB=0
THEN
DBMS_OUTPUT.
NEW_LI
NE(
);
DBMS_OUTPUT.
PUT_LI
NE(
B);
ELSE
DBMS_OUTPUT.
NEW_LI
NE(
);
DBMS_OUTPUT.
PUT_LI
NE(
B);
ENDI
F;
END;
Output
1
0
GET_LI
NES
Exampl
e
Output
ENABLE/
DISAB
LE
Exampl
e
DECLARE
AN
UMBER;
BUF
FER_SI
ZENUMBER:
=20000;
BEGI
N
A:
=10;
DBMS_OUTPUT.
DI
SABLE;
DBMS_OUTPUT.
PUT_LI
NE(
A);
A:
=A+1
0;
DBMS_OUTPUT.
ENABLE(
BUF
FER
_SI
ZE)
;
DBMS_OUTPUT.
PUT_LI
NE(
A);
END;
Output
20
UTL_F
ILE
Thispackageisusedtoaccessoperati ngsystemf i
les.Withthispackageyoucanreadf romand
writetooperati ngsystemf iles.
UTL_FI
LEconsistsoff unctions( FOPEN,I
S_OPEN)&procedures
(GET_LI
NE,PUT,PUT_LINE,PUTF,NEW_LI
NE,FFLUSH,
FCLOSE,FCLOSE_ALL).Itcontainssevenexception
namedasI NAVLID_PATH,I
NVALID_MODE,I
NVALID_F
ILEHANDLE,I
NVALID_OPERATION,READ_ERROR,
WRITE_ERRORandI NTERNAL_ERROR.
UTL_HTTP
Exampl
e
DECLARE
xutl
_http.
html
_pi
eces;
BEGI
N
x:
=utl
_http.
request_pi
eces(
'http:
//www.
oracl
e.com/
',1
00)
;
dbms_output.
put_l
ine(
x.count|
|'
pieceswereretri
eved.
'
);
dbms_output.
put_l
ine(
'wi
thtotall
ength'
);
I
Fx.
count<1
THENdbms_output.
put_l
ine(
'0'
);
ELSEdbms_output.
put_l
ine
(
(2000*(
x.count-1
))+l
ength(
x(x.
count)
));
ENDI
F;
END;
Output
1
7pi
eceswereretri
eved.
wi
thtotall
ength
33095
UTL_TCP
UTL_MAI
L
TheUTL_MAILpackageprovi
desasimpleAPI
toallowemailtobesentf
romPL/SQL.
Inpri
or
versi
onsthiswaspossibleusi
ngtheUTL_SMTPpackage(
shownhere),
butthi
srequired
knowledgeoftheSMTPprotocol.
TheUTL_MAI
Luti
li
tyi
susedtosende-mai
landmanagee-mai
lwhi
chi
ncl
udescommonl
yusede-
mailfeatures,suchasattachments,
CC,
BCC…etc.I
thasSEND,
SENDATTACHRAW,
SENDATTACH
VARCHAR2procedures.
Thepackagei
sloadedbyrunni
ngthef
oll
owi
ngscri
pts.
CONNsys/
passwordASSYSDBA
@$ORACLE_HO
ME/
rdbms/
admi
n/utl
mai
l.
sql
@$ORACLE_HO
ME/
rdbms/
admi
n/prvtmai
l.
plb
GRANTEXECUTEONUTL_MAI
LTOtest_user;
I
naddi
tiontheSMTP_OUT_SERVERparametermustbesettoi
denti
fytheSMTPserver.
CONNsys/
passwordASSYSDBA
ALTERSYSTEMSETsmtp_out_server='
smtp.
domai
n.
com'
SCOPE=SPF
ILE;
SHUTDO
WNI
MMEDI
ATE
STARTUP
Wi
ththeconf
igurati
oncompl
etewecannowsendamai
l.
BEGI
N
EX
ECUTEI
MMEDI
ATE'
ALTERSESSI
ONSETsmtp_out_server='
'
192.
168.
152.
1'
'
';
UTL_MAI
L.
send(
sender=>'
suresh
_ji
@yahoo.
com'
,
reci
pients=>'
suresh_j
i@yahoo.
com'
,
subj
ect=>'
TestMai
l'
,
message=>'
Hel
loWorl
d',
mi
me_type=>'
text;
charset=us-asci
i'
);
END;
PL/
SQLCOLLECTI
ONS:
Coll
ecti
onisanorderedgroupofelements,
allofthesametype.
Eachel
ementhasauni
que
subscri
ptthatdeterminesitsposi
tioni
nthecoll
ection.
Iti
sonedi
mension.
Typesofcol
lecti
onsare
1
) Associ
ati
vearray/PL/
SQLTabl
e
I
tcanbecalledasindex-by-tablewhichissetofkey-valuepai
rs.Eachkeyi
suni
queandkeycan
beei
therstringorinteger.
Itiscapableofholdi
ngun-specif
iednumberofelements.
2) Nestedtabl
e
Nestedtabl
eisacolumntypethathol
dssetofvalues.
Therowsaregi
venconsecuti
ve
subscri
ptsstarti
ngat1.
Itcanbestoredi
nadatabase.
3) Vari
abl
e-si
zearray/Records
V-arraystandsf
orvari
able-si
zearray.
Whenyoucreatev-arrayyoumustdecl
aremaxi
mum
numberofcolumns.
Theyusesequenti
alnumbersassubscri
pt.
SQLQUERYTUNNI
NG
AWRReport
AWRcanbeabbreviatedasautomaticworkloadreposi
tory.I
tisusedtocollectperformance
stati
sticsi
ncl
udingsessionhi
story,systemstati
stics,
timemodelstatisticsandobject
usagestati
sti
cs.
TKPROF
I
tisanoracl
eutil
itytodispl
aytracefi
le(.
trc)i
nhumanreadabl
eformat.
Anewtracef
ilei
s
createdf
oreverysessi
onandwhichcontai
nssessi
ondetai
ls.
EXPLAI
NPLAN
I
tdisplaysexecuti
onplanchosenbyoracl
ef orSELECT,
INSERT,UPDATEandDELETE.Herewecan
seeoperationthathastakenplace,
costfortheoperation,noofrowsaf fected,whichobj
ect
i
sused,howmanybytesused, howmuchtimetakenandhowi thasbeenf i
ltered.
Itletusknow
eitherwhi
chofthesenestedl
oops,hashj
oinandsortmergeareusedorwhyiti
sbeenused.
It
showsyouthecosttakentoexecutequerybasedonthi
swetrytoopti mi
zethequery.
TYPEOFLOOPS
1
. NESTEDLOOPS
Thi
soperati
oni
susedwhenyouj
oinmul
tipl
etabl
esusi
ngi
ndex.
2. HASHJ
OIN
Thi
soperati
oni
susedwhenyouj
oinmul
tipl
etabl
eswi
thouti
ndex.
3. SORTMERGE
Thisoperati
onisusedwhenyoujoi
ntableotherthanequaltosymbol(i.
e.l
ike>,<,>=,<=)
.Sort
operational
onetakesplacewhenyouuseorderbyclause(i
.e.
withoutajoincondi
tion)&when
youuseaggregatefunctions(
or)groupfuncti
onsandifyouusebothjoi
n&orderbythensort
mergeoperationtakesplace.
HI
NTS
Hi
ntsareusedtof
orcethequerytorunonparti
culari
ndexorf
ulltabl
escantoreducecost.
Youmustspeci
fyi
ndexnameorfull(
tablename)between/*+*
/.
/
*+F
ULL(
TABLENAME)*
/usethi
storunf
ulltabl
escan
I
NDEXES- speakoni
ndex–
EXTERN
ALTAB
LE
Externaltablesenableustoreadf lat-fil
es( storedontheO/ S)usi
ngSQL.Theyhavebeen
introducedinOracle9iasanalternativetoSQL*Loader.Externaltabl
esareessentiallystored
SQL*Loadercontrolfil
es,butbecausetheyaredef i
nedastabl es,
wecanaccessourf lat-fil
e
datausi ngal
lavail
ableread-onlySQLandPL/ SQLoperations.Wecanalsoreadflat-fi
lesin
parallelandjoi
nf i
lestootherf i
lesortables,viewsandsoon.
Externaltableissi
milartooracletablebutyoucannotperformDMLoperati
onsandcannot
createindexonexternaltable.I
tisusedtomovedatainandoutofthedatabase.
Exampleyou
aregetting.csvfromanotherdepartmenteverydayandyouneedtoimportintodatabase.
Insteadofwritingcommandf il
eeverydaycreateexternaltabl
einwhi
chdatawillbedumped
byrunningthescript.
Externaltabl
esarecreatedusi
ngtheSQLCREATETABLE..
.
ORGANI
ZATI
ONEXTERNALstatement.
Whenyoucreateanexternaltabl
e,youspeci
fythefollowingattri
butes:
TYPE-speci
fiesthetypeofexternaltabl
e.Thetwoavailabl
etypesaretheORACLE_LOADER
typeandtheORACLE_DATAPUMPtype.
Eachtypeofexternaltabl
eissupportedbyi
tsownaccess
dri
ver.
1
.)TheORACLE_LOADERaccessdri
veri
sthedef ault.I
tcanperformonlydataloads,andthe
datamustcomef romtextdatafi
les.Loadsfromexternaltablestointernaltabl
esare
donebyreadingfromtheexternaltables'text-onl
ydatafiles.
2.
)TheORACLE_DATAPUMPaccessdri
vercanperf ormbothloadsandunloads.Thedatamust
comef rombinarydumpf i
les.
Loadstointernaltablesfromexternaltablesaredoneby
fetchi
ngf romthebinarydumpf i
les.
Unloadsfrominternaltablestoexternaltabl
es
aredonebypopulatingtheexternaltables'
binarydumpf i
les.
DEFAULTDI
RECTORY-specifi
esthedef aultl
ocati
onoff i
lesthatarereadorwri ttenby
externaltables.
Thelocati
onisspecifi
edwithadirectoryobject,
notadirectorypath.See
Locati
onofD atafi
lesandOutputFil
esf ormorei
nf ormati
on.
ACCESSPARAMETERS-describetheexternaldatasourceandimplementsthetypeofexternal
tablethatwasspecifi
ed.Eachtypeofexternaltablehasitsownaccessdriverthatprovi
des
accessparametersuniquetothattypeofexternaltable.SeeAccessParameters.
LOCATION-specifi
esthelocati
onoftheexternaldata.Thel
ocati
onisspecif
iedasali
stof
directoryobjectsandfil
enames.
Ifthedirectoryobj
ectisnotspeci
fied,
thenthedefaul
t
directoryobjectisusedasthefi
lelocati
on.
Step1
:
CreateF
lat-F
ile:
Exampl
e:empl
oyees.
dat
56-november,
15,
1980-baker- mary- al
ice-09/
01/
2004
87-december,
20,
1970-roper- l
isa- mari
e-01
/01
/1999
56-november,
15,
1980-baker- mary- al
ice-09/
01/
2004
87-december,
20,
1970-roper- l
isa- mari
e-01
/01
/1999
Step2:
Di
rectoryCreati
on:
SQL>CREATEDI
RECTORYxt_di
rAS'
d:
\oracl
e\di
r'
;
Di
rectorycreated.
Step3:
SetPermi
ssi
ontoDi
rectory:
Af
teradirectoryiscreated,
theusercreatingthedi
rectoryobj
ectneedstograntREADand
WRITEpri
vil
egesonthedirectorytootherusers.
GRANTREADONDI
RECTORYext_tab_di
rTOscott;
Step4:
Createtabl
eemp_detai
ls
CREATETABLEemp_detai
ls(emp_noCHAR(6),DOBdate,
first_namevarCHAR2(
20)
,mi
ddl
e_name
varCHAR2(
20),l
ast_namevarchar2(
20),hire_dateDATE);
Step5:
Creati
ngExternalTabl
ename:
exe_tabl
e_empl
oyee
createtabl
eexe_tabl
e_empl
oyee
emp_i
dchar(
5),
dobch
ar(
20)
,
f
irst_namechar(
20)
,
mi
ddl
e_namechar(
20)
,
l
ast_namechar(
20)
,
hi
re_datedate
organi
zati
onexternal
typeoracl
e_l
oader
def
aul
tdi
rectoryext_di
r_suresh
accessparameters
recordsdel
imi
tedbynewl
ine
f
iel
dstermi
natedby'
-'
mi
ssi
ngf
iel
dval
uesarenul
l
(
emp_i
dchar(
5),
dobch
ar(
20)
,
f
irst_namechar(
20)
,
mi
ddl
e_namechar(
20)
,
l
ast_namechar(
20)
,
hi
re_datechar(
10)date_f
ormatdatemask"
mm/
dd/
yyyy"
l
ocati
on(
'i
nfo.
dat'
)
)
;
Step6:
Loadthedataf
romtheexternaltabl
eexe_tabl
e_empl
oyeei
ntothetabl
eemp_detai
ls:
SQL>I
NSERTI
NTOemp_detai
ls(
emp_no,
first_name,
middl
e_i
niti
al,
last_name,
hire_date,
dob)
(
SELECTempl
oyee_number,
empl
oyee_f
irst_name,
substr(
empl
oyee_mi
ddl
e_name,
1,1
),
empl
oyee_l
ast_name,
empl
oyee_hi
re_date,
to_date(
empl
oyee_dob,
'
month,
dd,
yyyy'
)
F
ROMexe_tabl
e_empl
oyee)
;
Step7:
Sel
ect*f
romemp_detai
ls;
Sel
ect*f
romexe_tabl
e_empl
oyee;
Step8:
Loaddatai
nternaltabl
eemp_detai
lstoexternaltabl
eimport_empl
oyee.
createtabl
eexe_expo
organi
zati
onexternal
typeoracl
e_datapump
def
aul
tdi
rectoryext_di
r_sures
l
ocati
on(
'i
nf.
xls'
)
)as
sel
ectemp_i
d,
dob,
f
irst_name,
mi
ddl
e_name,
l
ast_name,
hi
redate
f
romsuresh
_emp;
SQLLOADER
SQLLoaderisabulkl
oaderuti
lityusedformovi
ngdataf
romexternalf
ilesi
ntotheoracl
e
database.
Itisusedforhi
ghperformancedatal
oader
1
) Loadmul
tipl
edataf
ilesi
ntosi
ngl
etabl
e.
2) Loadsi
ngl
edatai
ntomul
tipl
etabl
es.
Opennotepadandtypethi
s
CI
D,
CNAME
ABC,
XXX
1
0,ORACLE
20,
UNI
X
30,
SHELL
Savetheabovef
ilei
n.csv(
commaseparatedval
uef
ile)f
ormat.
Onceagai
nopennotepadandtypethi
s
LOADDATAI
NFI
LE'
C:
\New\
COURSE.
CSV'
I
NTOTABLECOURSE
F
IELDSTERMI
NATEDBY"
,
"
(
CID,
CNAME)
Savetheabovef
ilei
n.ctl
(controlf
ile)f
ormat.
Opencmdandtype
SQLLDRHR/
ADMI
NCONTROL=C:
\New\
SUBJ
ECT.
CTLSKI
P=1
Un-insertedrowscanbevi
ewi
n.badf
ilewhi
chwi
llbecreatedautomati
cal
lyduri
ngcompi
li
ng
inthesamepath.
SQLLoaderkeywords
1
) REPLACE
Beforeinsertingdatai
ntotabl
eusingsqlloaderthetabl
emustbeempty.I
nsteadofemptying
tablemanual l
yyoucoulduse‘
REPLACE’
keywordtodeleteallrowsi
natabl
ebeforeinserti
ngin
.ctlfi
le.
LOADDATAI
NFI
LE'
C:
\New\
COURSE.
CSV'
REPLACE
I
NTOTABLESQLL3
F
IELDSTERMI
NATEDBY"
,
"
(
CID,
CNAME)
2) APPEND
Thi
skeywordi
sentirelyoppositeto‘
RELPACE’
.Th
iskeywordi
susedtol
oaddatai
natabl
eeven
i
fthetabl
ealreadycontainsrows.
LOADDATAI
NFI
LE'
C:
\New\
COURSE.
CSV'
APPEND
I
NTOTABLESQLL3
F
IELDSTERMI
NATEDBY"
,
"
(
CID,
CNAME)
3) I
NFI
LE*
Thi
ssi
gni
fiesthatthedatai
spresentattheendofthecontrolf
ile.
LOADDATAI
NFI
LE*
APPEND
I
NTOTABLESQLL3
F
IELDSTERMI
NATEDBY"
,
"
(
CID,
CNAME)
BEGI
NDATA
001
,ORACLE
002,
UNI
X
007,
DOTNET
4) BEGI
NDATA
Thi
sindi
catesthatthi
sistheendofthecontroli
nformati
onandbegi
nni
ngofdata.
LOADDATAI
NFI
LE*
APPEND
I
NTOTABLESQLL3
F
IELDSTERMI
NATEDBY"
,
"
(
CID,
CNAME)
BEGI
NDATA
001
,ORACLE
002,
UNI
X
007,
DOTNET
5) F
ILLERPOSI
TION
Sqll
oaderal
lowsf
ilteri
ngparti
cul
arrowandi
nserti
ngsamef
iel
dintwodi
fferentrows.
LOADDATA
I
NFI
LE'
C:
\New\
COURSE2.
CSV'
REPLACE
I
NTOTABLEEMPL1
F
IELDSTERMI
NATEDBY"
,
"
(
EMPNO,
EMPNAME,
DEPT_SKI
PFI
LLERPOSI
TION(
1),
DI
SC,
DEPTNO
,
DEPTNA
ME)
6) BOUNDF
ILLER
I
tcanbeusedi
ftheski
ppedcol
umn'
sval
uewi
llberequi
redl
ateragai
n.
LOADDATA
I
NFI
LE'
C:
\New\
COURSE3.
CSV'
REPLACE
I
NTOTABLEEMPL1
F
IELDSTERMI
NATEDBY"
,
"
REC_SKI
PBOUND
FILLER,
TMP_SKI
PBOUNDF
ILLER,
TML_SKI
PBOUNDF
ILLER,
EMPNO"
(:
REC_S
KIP|
|
:TMP_SKI
P|
|:
TML_SKI
P|
|:
EMPNO)
",
EMPNAME
7) WHEN
‘
WHEN’
clausei
susedi
nSQ
Lloadertoi
mposecondi
tionduri
ngdatal
oadi
ng.
LOADDATA
I
NFI
LE'
C:
\New\
COURSE4.
CSV'
REPLACE
I
NTOTABLEEMPL1
WHEN(
01)
='1
'
F
IELDSTERMI
NATEDBY"
,
"
(
REC_SKI
PFI
LLERPOSI
TION(
1),
EMPNO,
EMPNAME)
I
NTOTABLEDEPT1
WHEN(
01)
='2'
F
IELDSTERMI
NATEDBY"
,
"
(
REC_SKI
PFI
LLERPOSI
TION(
1),
DEPTNO
,
DEPTNA
ME)
8) SKI
P
Youcanski
punwantedrecordsusi
ngthi
scommand
OPTI
ONS(
SKI
P=1
)
LOADDATAI
NFI
LE'
C:
\New\
COURSE.
CSV'
APPEND
I
NTOTABLESQLL3
F
IELDSTERMI
NATEDBY"
,
"
(
CID,
CNAME)
(
0R)
SQLLDRHR/
ADMI
NCONTROL=C:
\New\
SUBJ
ECT.
CTLSKI
P=1
9.
) F
IXEDRECORDF
ORMAT
LOADDATA
I
NFI
LE'
C:
\New\
COURSE5.
CSV'
REPLACE
I
NTOTABLEEMPL1
(
DEPTNAMEPOSI
TION(
02:
05)CHAR(
4),
DI
SCPOSI
TION(
08:
27)CHAR(
20)
1
0.) VARAI
BLERECORDF
ORMAT
LOADDATA
I
NFI
LE'
C:
\New\
COURSE5.
CSV'
REPLACE
I
NTOTABLEEMPL1
(
DEPTNAMEPOSI
TION(
02:
05)CHAR(
4),
DI
SCPOSI
TION(
08:
27)CHAR(
5)
STREAMRECORDF
ORAMT
LOADDATA
I
NFI
LE'
C:
\New\
COURSE7.
CSV'
"str'
|
\n'
"
REPLACE
I
NTOTABLEEMPL1
F
IELDSTERMI
NATEDBY'
;
'TRAI
LINGNULLCOLS
(
DEPTNAME,
DI
SC
onel
ine;
hel
lodearworl
d;|
twol
ines;
Dearworl
d,
hel
lo!
;
|
RealTi
meExampl
e
Atsomestageyouneedtoinsertbul
krecordi
ntodatabasewhichyouhavei
n.CSVf
ilewhi
ch
cannotbedonemanual
ly.
Thiscanbeachi
evedbyusi
ngSQLLoadertopreventtime.
DBMSPROF
ILER
Thebuil
t–inpackageal
lowsyoutoturnonexecutionprof
ili
nginasessi
on.Thenwhyyourun
yourcodeoracl
eusestabletokeeptrackofthedetail
edinf
ormationabouthowl ongeachl
ine
i
nyourcodetoexecute.Youcanthenrunqueri
esonthesetablesormuchpreferreduse
screensi
nproductsli
keTOADorSQLNavi
gatortopresentthedatainacleargraphicalf
ashi
on.
dbms_prof
ileri
soracl
esuppl
iedpackagewhi
chusef
ortunni
ngpl
sqlappl
icati
on.
throughthi
spackagewecantuneourpl
sqlprocedure,
tri
gger,
funti
ons.
andf
indoutwhere
pl
sqlspentmoretimetoexecute.
DBMS_PROF
ILERPackage:
Oracle8iprovidesanewtoolcal l
edPL/
SQLProfil
er.Thi
sisapowerf ultooltoanalyzea
Programuni texecutionanddetermi
netheruntimebehavior.
Theresul tsgeneratedcanthen
beevaluatedtof indoutthehotareasinthecode.Thi
stoolhelpsusidentif
yperf ormance
bottlenecks,aswellaswhereexcessexecutiontimeisbei
ngspenti
nthecode.
Theti
mespent
inexecutinganSQLstatementisalsogenerated.Thi
sprocessi
simpl
ementedwith
DBMS_PROF I
LERpackage.
Thepossi
bleprof
ilerstati
sti
csthataregenerated:
1
.Totalnumberofti
meseachl
inewasexecuted.
2.
Timespentexecuti
ngeachl
ine.
Thi
sincl
udesSQLstatements.
3.
Mini
mumandmaxi
mumdurati
onspentonaspeci
ficl
ineofcode.
4.
Codethati
sactual
lybei
ngexecutedf
oragi
venscenari
o.
DBMS_PROF
ILER.
START_PROF
ILER
TheDBMS_PROF
ILER.START_PROFI
LERtell
sOracletostartthemonitori
ngprocess.
Ani
denti
fier
needstobeprovidedwi theachrunthatisusedlatertoretri
evethestati
stics.
DBMS_PROF
ILER.
STOP_PROF
ILER
TheDBMS_PR
OFI
LER
.STOP_PROF
ILERtel
lsOracl
etostopthemoni
tori
ng.
DBMS_PROF
ILER.
FLUSH_DATA
Thedatacollectedf oranexecuti
onishel
dinthememory.Cal
li
ngthe
DBMS_PROF
ILER.FLUSH_DATArouti
netell
sOracletosavethi
sdatai
nprof
ilertabl
esandcl
ear
thememory.
Exampl
e:
I
nBasi
cOracleInstallati
on"dbms_profi
ler"
packagei
snotcreated.
Wehavetomanual
lycreate
thi
spackagesrunningbelowscripts.
connwi
thSY
Suserandrun"
PROF
LOAD.
SQL"
Located:
$ORACLE_HOME/
rdbms/
admi
nfol
der
SQL>connsys@hgcassysdba
Enterpassword:
Connected.
SQL>@ C:
\oracl
exe\
app\
oracl
e\product\
10.
2.
0\server\
RDBMS\
ADMI
N\prof
load.
sql
Packagecreated.
Grantsucceeded.
Synonymcreated.
Li
brarycreated.
Packagebodycreated.
Testi
ngf
orcorrecti
nstal
lati
on
SYS.
DBMS_PROF
ILERsuccessf
ull
yloaded.
PL/
SQLproceduresuccessf
ull
ycompl
eted.
Conntoappl
icati
onuserandrun"
PROF
TAB.
SQL"
,thi
sscri
ptcreatethreetabl
es.
Located:
$ORACLE_HOME/
rdbms/
admi
nfol
der
1
.PLSQL_PROF
ILER_RUNS
2.
PLSQL_PROF
ILER_UNI
TS
3.
PLSQL_PROF
ILER_DATA
SQL>connscott/
tiger@hgc
Connected.
SQL>@ C:
\oracl
exe\
app\
oracl
e\product\
10.
2.
0\server\
RDBMS\
ADMI
N\prof
tab.
sql
Tabl
ecreated.
Commentcreated.
Tabl
ecreated.
Commentcreated.
Tabl
ecreated.
Commentcreated.
Sequencecreated.
Howcanusedbms_prof
iler?
1
.Connectwi
thappl
icati
onuserwhi
chyouwanttoopti
mize.
Startdbms_prof
iler
SQL>execdbms_prof
iler.
start_prof
iler(
'Procedure_p1
')
;
I
nformati
oni
sstorei
nmemorysof
lashprof
ilertoupdatethei
rreposi
tory.
SQL>execdbms_prof
iler.
flush
_data(
);
Stopdbms_prof
iler
SQL>execdbms_prof
iler.
stop_prof
iler(
);
Vi
ewI
nformati
onGeneratedbydbms_prof
iler
Queryi
nbel
owvi
ews
1
.sel
ect*f
rompl
sql
_prof
iler_runs;
2.
sel
ect*f
rompl
sql
_prof
iler_uni
ts
3.
sel
ect*f
rompl
sql
_prof
iler_data
DBMSUTI
LITY
Usethisbuil
t-infunctiontocalculatetheelapsedti meofyourcodedowntothehundredthof
asecond.Thescriptstmr-otandpl utmr.pkg(availableonthebook’swebsite)offeran
interf
acetothi sfunctionthatall
owsyoutouse‘ timers’(basedonDBMS_UTILI
TY.
GET_TI
ME)i
n
yourcoed.Theymakei tpossibl
etoti meexactlyhowl ongacertai
noperationtooktorunand
eventocomparevari ousimplementationsofth esamerequi rements.
Exampl
e
DECLARE
NN
UMBER;
BEGI
N
N:
=DBMS_UTI
LITY.
GET_TI
ME;
DBMS_OUTPUT.
PUT_LI
NE(
N);
END;
Output
835379
Exampl
e
DECLARE
TI
ME_BEF
OREBI
NARY_I
NTEGER;
TI
ME_AF
TERBI
NARY_I
NTEGER;
BEGI
N
TI
ME_BEF
ORE:
=DBMS_UTI
LITY.
GET_TI
ME;
P1
(100)
;
TI
ME_AF
TER:
=DBMS_UTI
LITY.
GET_TI
ME;
DBMS_OUTPUT.
PUT_LI
NE(
TIME_AF
TER-TI
ME_BEF
ORE)
;
END;
Output
PRAGMA
Pragmai
sakeywordi
nOracl
ePL/
SQLthati
susedtoprovi
deani
nstructi
ontothecompi
le.
1)Pragamameansforce(l i
kei
tsaystocompilerforci
bledothi
soperati
on)
2)Itisusedf
orcommi ttingtheparti
cularbl
ock.
3)Wecan'troll
backthisPragamaautonomousblock
TypesOfPragmas:
-
1-AUTONOMOUS_TRANSAC
TION
2-EXCEPTI
ON_I
NIT
3-RESTRI
CT_REF
ERENCES
4-SERI
ALLY_REUSABLE
ORACLEF
LASHBACKQUERY
Fl
ashbackqueryall
owsausertovi
ewthedataquicklyandeasi
lythewayi
twasataparti
cular
ti
meinthepast,evenwheni
tismodi
fiedandcommitted,bei
tasingl
eroworthewhol
etable.
F
lashbacktechnol
ogi
esareappl
icabl
einrepai
ringthef
oll
owi
ngusererrors.
1.
) Erroneousormal
ici
ousDROPTABLEstatements
2.
) Erroneousormal
ici
ousupdate,del
eteorinserttransacti
ons
3.
) Erroneousormal
ici
ousbatchjoborwide-spreadappli
cati
onerrors
Configurati
onbef
oreusi
ngFlashbackQueri
es
Inordertousethisf
eature,
thedatabaseinstancehastobeconfi
gured.
Logontothedatabasewherethetesti stobeperformedandrunthefoll
owi
ngcommandat
theSQLprompts:
SQL>showparameterUNDO;
NAME TYPE V
ALUE
------------------------------------------------
undo_management stri
ng AUTO
undo_retenti
on i
nteger 900
undo_suppress_errors bool
ean TRUE
undo_tabl
espace stri
ng UNDO_TBSPC
Thiscommanddisplaysallthenecessaryparametersforusi ngtheFlashbackQueri
es.Thevalue
forUNDO_RETE
NTIONissetto900secondsi nthi
sexamplewhi chisthedef aultval
ueand
representsatleasthowl ongthesystemretainsundo.UNDO_RETENTIONandUNDO_TABLESPACE
aredynamicparameters,butUNDO_MANAGEMENTisnot,requiringshutdownandre-startof
databasei
nstancei
norderf
orautomati
cundomanagementtotakeef
fect.
I
naddi
tiontotheaboveyourDBAwi
llhavetogrant:
FLASHBACKpri
vilegetotheuserf
oral lorasubsetofobj
ects
Executeprivi
legesonthedbms_flashbackpackage
Usi
ngtheF
lashbackQuerywi
thASOFcl
ause:
Supposewewanttorecoverdatawehaveaccidental
lydeletedforsomeoftheempl
oyees
fromtheEMPLOYEEtabl
eandhavecommittedthetransaction.
SQL>INSERTI
NTOEMPLOYEE_TEMP
(SELECT*FROMEMPLOYEEASOFTI
MESTAMP(
'1
3-S
EP-048:
50:
58'
,
'DD-MON-YYHH24:
MI:
SS'
Usingapointintimeiswayofgoi ngback,anotherwayoftel li
ngthesystemhowf artogoback
istheuseofS CN-SystemChangeNumber. Theprocedureisthesameasearl i
er,tryingto
recoverlostdatausi ngtheDBMS_FLASHBACKutili
ty.Onl
ythistimeinsteadofusingtheti mewe
areusingthesystemchangenumber-SCNtoenterthef lashbackmode.Thi
sSCNnumbercanbe
obtainedbeforethetransactionisiniti
atedbyusingtheGET_SYSTEM_CHANGE_NUMBERf uncti
on
oftheDBMS_F LASHBACKutil
ityasfollows.
SQL>sel
ectDBMS_F
LASHBACK.
GET_SYSTEM_CHANGE_NUMBERf
romdual
;
SQL>I
NSERTINTOEMPLOYEE_TEMP
(SELE
CT*F ROMEMPLOYEEASOFSCN1
0280403339)
;
Oracle10Ghasenhancedthef lashbackfeaturef
urtherandhasturnedi
tintoamuchmore
powerf ulfeaturebyintroducingnumerousaddi
tions.
Someofthemorecommononesare
discussedhere.
1.
) F
lashbackTable
2.
) F
lashbackDrop
3.
) F
lashbackDatabase
4.
) F
lashbackVersi
onsQuery
5.
) F
lashbackTransacti
onQuery
1
.) F
lashbackTabl
e
Justli
ketheflashbackqueryhelpsretrieverowsofatable,FLASHBACKTABLEhel
psrestorethe
stateofatabletoacertainpointintimeevenifatablestructurechangedhasoccurredsince
then.
Thefoll
owi ngsimpl
ecommandwi lltakeustothetablestateatthespeci fi
edti
mestamp.
SQL>FLASHBACKTABLEEmployeeTO
TI
MESTAMP( '
13-SEP-048:
50:
58'
,
'DD-MON-YYHH24:
MI:SS'
);
Notonlydoesthiscommandrestorethetablesbutalsotheassoci
atedobj
ectsl
ikei
ndexes,
constrai
ntsetc.
2.
) F
lashbackDrop
SQL>F LASHBACKTABLEEMPLOYEETOBEF
OREDROP;
Bringi
ngbackdroppedtabl escoul
dnotbeanyeasi
erthanthi
s.
3.
) RECYCLEBI
N
I
tisworthwhi letotakeal i
ttledetourandf amili
arizeourselveswiththef eatureinOracl
e
10gthatenablsustof l
ashback.Oracl
ehasintroducedtheRECYCLEBI Nwhichisal ogi
calenti
ty
toh ol
dallthedeletedobj ectsandworksexacl tyliketherecylcebinprovi
dedi nWindows
operatingsystemf orexampl e.Al
lthedeletedobjectsarekeptntherecyl cebin,these
objectscanberetri evedfromtherecyclebi nordel etedpermanentlybyusingthePURGE
command. Ei
therani ndi
visualobjectl
ikeatabl eorani ndexcanbedeletedfromtherecycl ebi
n:
SQL>PURGETABLEEmployee;
orthewholerecylcebincanbe'
empti
edout'
byusi
ngthePURGEcommand:
SQL>PURGErecycl
ebi
n;
I
fyoutakeal
ookatthecontentsoftherecycl
ebi
nusi
ngthef
oll
owi
ngquery,
SQL>sel
ectOBJ
ECT_NAME,
ORI
GINAL_NAME,
TYPEf
romuser_recycl
ebi
n;
OBJ
ECT_NAME ORI
GINAL_NAMETYPE
------------------------------------------------------------------
BI
N$G/
gHMi
grTRqHQukZSI
pSLw==$0 EMPOLY
EE TABLE
BI
N$1
UiHeUR7SymGHo20pTf
GXA
==$0 EMPLOY
EE TABLE
BI
N$6d6677f
5T+K++npt+5p/
jQ==$0 EMP_I
DX1 I
NDEX
4.
) F
lashbackdatabase
FlashRecoveryAreacreatedbytheDBA, i
stheallocationofspaceonthedisktoholdallthe
recoveryrelatedfil
esinone, central
izedplace.
F l
ashRecoveryAreacontainstheFlashback
Logs,RedoArchivel
ogs,backupsf i
lesbyRMANandcopi esofcontrolfi
les.
Thedestinationand
thesizeoftherecoveryareaaresetupusi ngthedb_recovery_fil
e_destand
b_recovery_fil
e_dest_sizeiniti
ali
zatinparameters.Nowwhenthesetupi scompl
ete, l
et'ssee
howthef lashbackdatabaseisused.
F
orthi
stestsupposeth
atatransacti
onranthatmadesi
gni
ficantchangesti
thedatabase,
yetthisisnotwhattheuserintended.Goi
ngbackandretri evi
ngindivi
dualobjectsandthen
recovernigandrestori
ngtheori
ginaldatacanbeaveryextensi ve,yettimeconsumingand
error-proneexercise.
Iti
stimetousetheF LASHBACKDATABASE.
Fi
rstthefl
ashbackisenabl
edtomakeOracl
edatabaseenterthefl
ashbackmode. Thedatabase
mustbemountedExclusi
veandnotopen.
Thedatabasehastobei
ntheARCHIVELOGMODEbefore
wecanusethi
sf eature.
Thi
sisshownasbel
ow.
SQL>ALTERDATABASEARCHI
VELOG;
NowstartupthedatabaseinEXCLUSI
VEmode.
SQL>SHUTDOWNI
MMEDI ATE;
SQL>STARTUPMOUNTEXCLUSI
VE
Nowentertheflashbackmode(thedatabaseshoul
dnotbeopenatthi
sti
me)
>ALTERDATABASEFLASHB
ACKON;
I
ssuetheflashbackcommandandtakethedatabasetothestatei
twasi
n,onehourago.
SQL>Flashbackdatabasetoti
mestampsysdate-( 1/24)
;
Afterthesystemcomesbackwi thFLASHBACKCOMPLETE,openthedatabase.
SQL>ALTERDATABASEOPENRESETLOGS;
Nowi fyouselectfromanyofthetablesthatwereaf f
ected,
youwillseethattheaffected
tablesareintheorigi
nalstate,
i.
e.anhourago.
Andonceagai
n,wehavetheoptionofusingSCN
insteadoftimestamp.
PL/SQL_WARNI
NGS
Compile-Ti
meWarni
ngs:
Oraclecannowproducecompile-timewarningswhencodei sambiguousorineffici
entbe
settingthePLSQL_WARNI
NGSparameterateitherinstanceorsessionlevel
.ThecategoriesALL,
SEVERE,I
NFORMATI
ONALandPERFORMANCEcanbeusedtoal terthetypeofwarni ngsthatare
produced.
--Instanceandsessi
onlevel.
ALTERSYSTEMSETPLSQL_WARNI
NGS='
ENABLE:
ALL'
;
ALTERSESSI
ONSETPLSQL_WARNI
NGS='
DI
SABLE:
PERFORMANCE'
;
--Recompi l
ewi thextrachecki
ng.
ALTERPROCEDUREhell
oCOMPILEPLSQL_WARNI
NGS='
ENABLE:
PERF
ORMANCE'
;
--Setmuti pl
evalues.
ALTERSESSI
ONSETPLSQL_WARNI
NGS='
ENABLE:
SEVERE'
,
'DI
SABLE:
PERF
ORMANCE'
,
'DI
SABLE:
I
NFORMATI
ONAL'
;
--UsetheDBMS_WARNI NGpackageinstead.
EXECDBMS_WARNI
NG.SET_WARNING_SETTING_STRI
NG('
ENABLE:
ALL'
,'
SESSI
ON')
;
Thecurrentsettingsassociatedwi theachobjectcanbedisplayedusi
ngthe
[USER|
DBA|
ALL
]_PLSQL_OBJECT_SETTINGSviews.
Toseeatypi
calexampl
eofthewarni
ngoutputrunthef
oll
owi
ngcode.
ALTERSESSI
ONSETPLSQL_WARNI
NGS='
ENABLE:
ALL'
;
CREATEORREPLACEPROCED UREtest_warni
ngsAS
l_dummyVARCHAR2( 10):='
1';
BEGI N
IF1=1THEN
SELECT'2'
INTOl _dummy
FROM dual ;
ELSE
RAISE_APPLI
CATI
ON_ERROR(-20000,
'l
_dummy!=1!
'
);
ENDI F;
END;
/
SP2-0804:
Procedurecreatedwi
thcompi
lati
onwarni
ngs
SHOWERRORS
LI
NE/COLERROR
-----------------------------------
9/5 PLW-06002:
Unreachabl
ecode
Warni
ngCategory:
1.
) --severe
SELECTdbms_warni
ng.
get_category(
5000)
FROMdual;
2.
) --i nformati
onal
SELECTdbms_warni
ng.
get_category(
6002)
FROMdual;
3.
) --perf ormance
SELECTdbms_warni
ng.
get_category(
7203)
FROMdual;