0% found this document useful (0 votes)
51 views129 pages

SQL_COMPLETE

The document discusses Oracle 11g, a relational database product that utilizes various languages such as SQL and PL/SQL for data management. It outlines the differences between data and information, the importance of data integrity, security, and indexing, and introduces the concept of Database Management Systems (DBMS) architecture. Additionally, it describes the three levels of DBMS architecture: external, conceptual, and internal, emphasizing data independence and the various data models used in database design.

Uploaded by

ameershaikh5009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views129 pages

SQL_COMPLETE

The document discusses Oracle 11g, a relational database product that utilizes various languages such as SQL and PL/SQL for data management. It outlines the differences between data and information, the importance of data integrity, security, and indexing, and introduces the concept of Database Management Systems (DBMS) architecture. Additionally, it describes the three levels of DBMS architecture: external, conceptual, and internal, emphasizing data independence and the various data models used in database design.

Uploaded by

ameershaikh5009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

ORACLE11G(

gri
d)
Dat
a:27/
2/2015

Ther
ear
emai
nlyt
wodi
ff
erentt
ypesofdat
abasel
anguagei
sORACLE.Theyar
e:

SQL(STRUCTUREDQUERYLANGUAGE)
PL/SQL(PROCEDURALLANGUAGEext
ensi
onofSQL)
DynamicSQL.
(opt
ional
)

ORACLEisaRelati
onalDat
abasepr
oductwhi
chi
susedt
ostor
edat
aper manent
lyi
nsecondar
yst
orage
dev
ices.I
fyouwantt
ooperat
eORACLEthenwear
eusi
ngf
oll
owi
ngl
anguages:

SQL:Iti
snon-pr
ocedurall
anguage.
PL/SQL:Iti
saprocedural
language.

Al
lor
gani
zat
ionsst
oresamet
ypeofdat
a.

DATA:I
tisacol
l
ect
ionofRawf
act
s.

Exampl
e:101di
nesh 2000

102mahesh3000

I
nabov
eexampl
e,t
her
enomeani
ngf
uldat
asuchdat
aisknownasRawf
act
s.

I
NFORMATI
ON:I
tisacol
l
ect
ionofmeani
ngf
uldat
aorpr
ocesseddat
a.

Exampl
e:EmpI
D Ename Sal
ary

101 di
nesh 2000

102 mahesh 3000

I
ntheabov
eexampl
e,t
her
eismeani
ngf
uldat
awhi
chi
sint
abl
efor
matwhi
chconsi
stoft
hreedi
ff
erent
f
iel
ds.

DATASTORE:I tisapl
acewher ewecanst oredat
aori nf
ormation.
Books&Paper s
Fl
atf i
les
Database
FLATFI LES:Thisisat
radit
ionalmechanism whi
chisusedt ostoredat
aorinfor
mat
ioni
nindi
vi
dual
unrel
atedf i
l
es.Thesef
ilesarealsocal
ledasFlatFi
les.DrawbacksofFlatf
il
es:

Dat
aRetri
eval
Dat
aRedundancy
Dat
aInt
egrit
y

MUARLISI
R 2015
1

Cl
assi
fi
cat
ion:
Publ
ic
Dat
aSecuri
ty
Dat
aIndexi
ng

DataRetri
eval:I
fwewantt or
etr
iev
edat
afr
om f
latfi
lest
henwemustdev el
opappl
icat
ionprogr
am i
n
hi
ghl ev
ellanguages,wher
easifwewantt
oret
riev
edatafrom dat
abasesthenweareusingSequel
Language.

SEQUEL(
Str
uct
uredEngl
i
shQuer
yLanguage)

Dat
e:28/
2/2015

DataRedundancy:Somet
imeswear emaintaini
ng multi
plecopi
esoft hesamedat aindiffer
ent
l
ocati
onst
hisdataisal
socal
ledasDupli
cat
edat aorRedundantdata.I
nFl
atfi
lesmechani
sm whenwe
ar
emodifyi
ngdatainonel
ocati
oniti
snoteff
ectedinanotherl
ocati
on.Thi
siscal
ledI
NCONSISTENCY.

Dat
e:2/
3/2015

I
ndat abases, ever yt ransact i
oni nternallyhav ing4pr oper ti
es.Thesepr opertiesareknownas
ACIDpr operti
es.
ACIDPr operti
es:
AmeanAt omi city( ROLLBACK)
CmeanConsi stency
ImeanI solati
on
DmeanDur abili
ty( COMMI T)
Thesepr opertiesonl yautomat icallymai ntai
nsconsi stentdat ai ndatabases.
DataI ntegrit
y :Int egri
tymeanst omai ntainpr operdat a.I fwewantt omai nt
ainpr operdatathenwear e
defi
ningsetofr ules,theser ulesar ealsocal l
edas“Busi nessrules”.Indat abases,wear emaintai
ning
properdat ausi ng„ const raints‟,„tr
igger s‟.Ifwewantt omai ntai
npr operdat ai nf l
atfi
leswemust
developappl icat ionpr ogramsi nhighlev el l
anguagesl ikeCOBOL, JAVA, ETC…..
DataSecur it
y:Dat ast oredi nf l
atfil
escannotbesecur edbecausef latfi
lesdoesn‟ tprovi
dessecurit
y
mechani sm.Wher easdat abasespr ovi
des“ ROLEbasedsecur i
ty”.
DataI ndexing:I fwewantt or etri
evedat av er
yqui cklyf rom databaset henwear eusingindexing
mechani sm.Wher easf latfil
esdoesn‟ tpr ov i
deindexi ngmechani sm.

Toover
comeal
ltheaboveprobl
ems,anewsof
twar
eusedbyal
lor
gani
zat
iont
ost
oredat
aori
nfor
mat
ion
i
nsecondar
yst
oragedev
ices.Thi
siscal
l
edDBMSsoft
ware.

DBMS(
DATABASEMANAGEMENTSYSTEM)
:

I
tisacol
l
ect
ionofpr
ogr
ams(
S/W)wr
it
tent
omanagedat
abase.

Exampl
e:ORACLE,
FOXPRO,
DB2,
TERADATA,
SQLSERVER,
SYBASE,
MYSQL,
INGRESS,
INFORMI
X,
SQLLI
TE……etc;

MUARLISI
R 2015
2

Cl
assi
fi
cat
ion:
Publ
ic
I
nfil
ebasedappr
oach,ev
eryappl
i
cat
ionpr
ogr
am i
ntheor
gani
zat
ionmai
ntai
nit
sownf
il
esepar
atef
rom
ot
herappl
i
cat
ionprogr
am.

FI
LEbasedappr
oach:

Her
ecust
noandcustnameat
tri
but
esar
edupl
i
cat
edat
a.

THI
SISOLDAPPROACH

Oncewear einstal
l
ingDBMSsof twareintooursy stem t
henaut omati
cal
lysomepl acei screatedinhard
di
sc.Thisiscal
led“Physi
calDatabase”
.Andal soaut omati
call
yanuseri nt
erf
aceiscr eated.Throughthe
useri
nter
facewecanal sodir
ectl
yinter
acti
vewi t
ht hedatabaseorindi
rectl
yint
eracti
vewi ththedatabase
usi
ngappli
cati
onprogramsinhighlevel
languages.

MUARLISI
R 2015
3

Cl
assi
fi
cat
ion:
Publ
ic

AFTERI
NSTALLI
NGDBMSSOFTWARE”

Dat
e:3/
3/2015

DATABASE:Iti
sanor
gani
zedcol
lect
ionofi
nter
rel
ateddat
ausedbyappl
icat
ionpr
ogr
am i
nanorgani
zati
on.
Oncedatastor
edi
ndat
abasei
tcanbesharedbynumberofuser
ssimult
aneousl
yandal
sothi
sdatacanbe
i
ntegr
ated.

DBMSAr chi
tecture:Ameri
canNati
onalSt
andardI
nstit
ute(
ANSI )hasestabli
shedt
hreel
evelar
chit
ect
urefor
database.Thisarchit
ect
ureisal
socal
ledas“ansi
/sparc”(
StandardPlanningAndRequi
rementsCommitt
ee)
archi
tectur
e.

Mai
nobject
iveofDBMSar
chi
tect
urei
stosepar
ateuser
svi
ewoft
hedat
abasef
rom t
hewher
ephy
sical
l
yit
i
sst
ored.

Thi
sar
chi
tect
uremai
nlyconsi
stoft
hreel
evel
s.Theyar
e:

Ext
ernal
lev
el
Concept
uall
evel
I
nter
nall
evel

MUARLISI
R 2015
4

Cl
assi
fi
cat
ion:
Publ
ic
DBMSAr
chi
tect
ureorThr
eeLev
elAr
chi
tect
ureDBMS

ar
chi
tect
urepr
ovi
des“
DATAI
NDEPENDENCE”
.

Dat
aIndependence:Upperl
evel
sareunaf
fect
edbychangesi
nt hel
owerlevel
siscal
l
edas“
Dat
a
I
ndependence”
.DBMSar chi
tect
urehav
etwotypesofDat
aIndependences:

LogicalDataIndependence
PhysicalDataIndependence
LogicalDataIndependence:Changest otheconcept uall
eveldonotrequiredtochangetotheext
ernal
l
evel t
hisiscalledLogicalDataIndependence.
Exampl e:Addinganewent i
tyinconceptualleveldoesnotef f
ecti
nexternallevel.
PhysicalDataI ndependence:Changest otheinternall
eveldonotrequir
edt ochangesinconcept
ual
l
evel.Thisiscal l
edPhy si
calDataIndependence.
Exampl e:Addingani ndextotheinternal
leveli
tisnotaf f
ectedinconceptuallevel
.

CONCEPTUALLEVEL:I tdescr
ibeslogi
calr
epresentat
ionoft
hedat
abase.Concept
uallev
eldef
inest
ypeof
dat
astor
ingindatabaseandalsodef i
neswhattypeofdatadoesnotst
oreindatabaseusi
ngconstr
aint
s
andal
sospecif
iestherel
ati
onshipbetweendatait
ems.

NOTE:Thisl
eveldoesnotdef
inehowdat
aisst
oredi
ndat
abase.I
nrel
ati
onaldat
abaseswear
edef
ini
ng
concept
uall
evel
sthrought
abl
es.

EXTERNALLEVEL:Thi sleveldescri
besenduserview oft
hedatabase.i
.e.
,int
hisl
evelsomegroupof
usersaccessonl
ypartofthedatabase.I
nthi
slev
elonlywearedef
ini
ngtheviewandt
hosev i
ewsgi
vento
thenumberofusers.

MUARLISI
R 2015
5

Cl
assi
fi
cat
ion:
Publ
ic
INTERNALLEVEL:Int
ernall
eveldescri
beshowphysi
cal
l
ydat ai
sstoredi
ndatabase.Thi
slevelishandl
ed
bydatabaseadmi
nist
rat
oronly.I
nrelat
ional
dat
abasesi
ndexes,
clust
erar
eavail
ableini
nter
nallevel
.

Dat
a:4/
3/15

DATAMODELS:Howdat ai
srepr
esent
edattheconcept
uall
eveldef
inedbymeansof“
Dat
aModel
”int
he
hi
stor
yofdat
abasedesi
gnt
hreedat
amodelshavebeenused.

Hierar
chical
DataModel
NetworkDataModel
Relati
onalDataModel

DBMSARCHI
TECTURE

Hier
archicalDataModel :Thismodeli
ntr
oducedin1960.Inthi
sdat amodelorgani
zesdat
aintreeli
ke
str
ucture,wearerepresenti
ngdatai
nparentchi
ldhi
erar
chy
.Inthi
sdatamodelalsodatai
srepr
esent
edin
theformatofrecordsandalsorecor
dtypeisal
sosameastableinrel
ati
onal
datamodel.

MUARLISI
R 2015
6

Cl
assi
fi
cat
ion:
Publ
ic
Thi
sDat
amodelhavingmor edupl
icat
erecor
dsbecausethi
sdatamodeli
simplementedbasedon
one-t
o–manyrel
ati
onshi
ps.Thatiswhyinthi
sdat
amodel al
wayschi
l
dsegmentsar
er epeat
ed.

I
nthi
sdatamodelproduct
s,weareretr
iev
eddataver
yslowl
ybecausei
nthi
sdat
amodelpr
oduct
s
dat
abaseser
ver
ssear
chingdatabasedonrootnodeonwar
ds.

I
n1960,
IBM i
ntr
oducedI
MS(I
nfor
mat
ionManagementSy
stem)pr
oductbasedonHi
erar
chi
calDat
a
Model
.

I
fwewantt
ooper
atehi
erar
chi
cal
dat
amodel
product
sthenwear
eusi
ngpr
ocedur
all
anguage.

HI
ERARCHI
CALDATAMODEL

RELATI
ONALDATAMODEL

MUARLISI
R 2015
7

Cl
assi
fi
cat
ion:
Publ
ic
Dat
e:5/
3/15

NetworkDataModel:In1970‟s,CODASYL( ConferenceOrDataSystem Language)commi t


teei
ntr
oduced
networkdat
amodel.Thisdatamodel i
simplement edbasedonmany
–t o–manyr el
ati
onships.Inthisdatamodelal sodataisstoredi
nf ormatofrecords.Andalsorecor
ds
ty
pei sal
sosameast ableinRelati
onalDatamodel .In1970‟
sIBM companyi nt
roducedIDMS(I
nformati
on
DataManagementSy stem)basedonnet workdat amodel.Ifwewantt ooperatenetworkdatamodel
product
sthenwemustusepr ocedurall
anguage.

NETWORKDATAMODEL

Rel
ati
onalDat
aModel:I
n1970,E.
F.Coddint
roducedRel
ati
onalDataModel.I
nthisdatamodelwear
e
st
ori
ngdatai
n2-di
mensi
onal
tabl
es.Rel
ati
onaldat
amodelmainlyconsi
stof3component
s.

Coll
ect
ionofObjects.
SetofOperat
ors.
SetofI
ntegri
tyrul
es.

I
fwewantRel
ati
onal
Dat
aModel
product
sthenwear
eusi
ngNon-Pr
ocedur
alLanguage“
SQL”
.

MUARLISI
R 2015
8

Cl
assi
fi
cat
ion:
Publ
ic
In1977Larr
yEll
isi
on,BobMi ner
,EdOatesfoundednewcompany“Sof twar
eDev
elopment
Laborat
ori
es”(
SDL)
In1978SDLIntr
oducedoracleversi
on1(neverr
eleased).
In1979SDLnamechangedi nt
oRSI(Rel
ati
onalSoftwareIncor
por
ati
on)
.
In1982RSInamechangedi ntoOracl
eCorporat
ion.

ORACLEVERSI ONS
1)Oracl e2. 0->1979
->Firstpubl icrel ease
->Int hi
s2. 0onl ybasi cSQLf unct
ional
it
yi sther
e“joi
ns”
.
Or acle3. 0->1983
->Rewr i
tteninCl anguage.
->Commi t,Roll back.
Or acle4. 0->1984- >
ReadConsi stancy
->exp/ imput i
li
t ypr ograms[ export/
impor t
].
Or acle5. 0->1985
->Clientser verar chitecture.
Or acle6. 0->1988- >
I
ntroducedPL/ SQL- >Row
l
ev ellocks.
Or acle7. 0->1992- >
Roles
->Integrityconst raints.->
StoredPr ocedur es->
StoredFunct ions- >
Packages
->Trigger s
->Dat at y
pe“ var char”changedi nto“varchar2”
->Truncat etabl e.
Or acle7. 1->1994
->Introduceddy nami cSQL
->ANSI /
ISOSQL- 92.
Or acle7. 2->1995
->Inli
nev iewsorsubquer iesusedi nfrom clause.
->refcur sor( cur sorv ari
abl e)
Or acle7. 3->1996- >
Bitmapi ndexes.- >utl_f
ile
package.
Or acl e8.0- >1997- >
Objectt echnol ogy
->Col umnsi ncr easedperat ableupto“1000” .
->nest edt able, var r
ay .
->Insteadoft rigger s.
MUARLISI R 2015
9

Cl
assi
fi
cat
ion:
Publ
ic
Or acle8i( i-inter net)->1999->
Mat erializedv iews.
-
>Funct ionbasedi ndexes
-
>Casecondi tional statements.-
>
Anal yti
cal funct i
ons.
-
>Aut onomoust rasact i
ons->
roll
up, cube.
-
>BULKBI ND
Or acle9i- >2001
-
>9i joinsoransi joins
-
>mer gest atement s.
-
>mul t
i tabl ei nser t
-
>f lashbackquer ies.
-
>Renami ngacol umn
Or acle10g( g-gr id)->2003->
recyclebi n
-
>f lashbackt abl e- >
i
ndicesofcl ause- >
regularexpr essi ons- >
wm_ concat ().
Or acle11g- >2007
-
>I ntroducedcont inuest atementinPL/SQLloops
-
>Readonl yt abl es
-
>Vi r
tual Col umns
-
>Pi vot()f uct i
on.
-
>Compoundt ri
gger
-
>enabl e,di sabl ecl ausesusedi ntri
ggerspeci
fi
cati
on->
foll
owcl ause
-
>Sequencesusedi nPL/ SQLwithoutusi
ngdualtabl
e.
-
>Named, mi xednot ationsareusedinasubprogram execut
edusedsel
ectst
atement
.
Date:6/ 3/ 15

MUARLISI
R 2015
10

Cl
assi
fi
cat
ion:
Publ
ic
SQL(STRUCTUREQUERYLANGUAGE)
SQLi
sanNon-pr ocedurallanguage, whichisusedt
ooper at
eallrel
ati
onal
databaseproduct
s.
I
n1970,E. F.CoddintroducedRel ati
onalDataModel.AndalsoDSL/Alphalanguage.I
n
I
BM ,“Sy stem/ R”team modi f
iedDSL/ Alphal
anguagei nt
o“ SQUARE”.AgainIBM companychange
SQUAREi ntoSEQUEL( StructuredEngli
shQueryLanguage).Thenonly
SEQUELbecame“ SQL” .
I
n1986int roducingANSIi nSQL
I
n1987int roducingISOi nSQL
I
n1989r eleasingfir
stv ersionofANSI /
ISOSQL89t hati
sSQL89.
I
n1992ANSI /
ISOSQL92- >SQL92.
I
n1999ANSI /
ISOSQL99- >SQL99.
I
n2003ANSI /
ISOSQL03- >SQL03.

SQLSubLanguagesi
nev
erydat
abase:

Dat aDefiniti
onLanguage( DDL):
 Creat e
 Alter
Drop
 Truncat e
 Rename( oracle9i)
Dat aMani pulati
onLanguage( DML):
 Insert
 updat e
 delete
 mer ge(oracle9i)
Dat aRetrievalLanguage(DRL)orDataQuer
yLanguage(
DQL)
:
 SELECT
Transact i
onalCont r
olLanguage(TCL):
Commi t
Rollback
Sav epoi
nt
Dat aCont rolLanguage(DCL):
 Grant
Revoke

Oracle10g,11g,12c.(
Enter
pri
seEditi
on)
Username:scott
Password:ti
ger
Err
or:Accountlockedmessagedisplayedf
orf
ir
stt
ime.So,
agai
nwehav
etoconnect
.
Username:\sy sassysdba
Password:sys
SQL>alteruserscottaccountunl
ock:
SQL>connscot t/t
iger
Enterpassword:ti
ger
MUARLISI R 2015
11

Cl
assi
fi
cat
ion:
Publ
ic
Conf
ir
m passwor
d:t
iger

Dat
e:7/
3/2015

Dat
aTy pes:Datat
ypesspeci
fi
est
ypeofdat
awi
thi
nat
abl
ecol
umnOr
acl
ehav
efol
l
owi
ngdat
aty
pes:
Number (p,
s)
Charv ar
char
2(maxsi
ze)
Date.

p pr eci sion( t
otalnumberofdi gi
ts)
s scal e(i tisusedt ost orefixed,fl
oatingpoi ntnumber s).
Sy ntax: col umnnamenumber (p,
s)
Exampl e: SQL>cr eatet abletest(snonumber (7,2))
;
SQL>i nser ti ntotestv alues( 12345.67);
SQL>sel ect*f rom t
est ;
Sno
---
----
--
12345. 67
SQL>i nser tint otestvalues( 123456.7)
Error :valuel argerthanspeci fi
edpr eci
sional l
owsf orthi
scolumn.
Not e:whenev erwear eusi ngnumber (p,s)thent otalnumberofdi gi
tsbef
oredecimalplacesupto“p-
s”
numberofdi gi t
s.
[eg:-p- s=>7- 2=5]
AfterDeci mal :
SQL>i nser tint otestvalues( 12345.6789) ;
SQL>sel ect*f rom t
est ;
Sno
---
----
--
----
12345. 68
SQL>i nser tint otestvalues( 12345.6725) ;
SQL>sel ect*f rom t
est ;
Sno
---
----
--
---
12345. 67
Not e:whenev erwear eusi ngnumber (p,s)andal soi fwearepassingmorenumberofdi gi
tsaft
erdeci
mal
placet henor acleserveronl yaut omaticall
yroundedt hatnumberbasedonspecif
ied“scal
e”.
Number (
p) :Iti susedtost oref i
xednumber sonl y
.Maxi mum lengt
hofthepr
ecisi
onisupt o“38”
.
Exampl e: SQL>cr eatet abletest1(snonumber (7));
SQL>i nser tint otest1v alues(99.9);
SQL>sel ect*f rom t
est 1;
Sno
MUARLISI
R 2015
12

Cl
assi
fi
cat
ion:
Publ
ic
--
--
---
100
SQL>i nsertintotest 1val
ues(99.
4);
SQL>sel ect*f rom test1;
Sno
--
--
---
--
--
99
Char :I
tisusedt ostorefi
xedlength“alphanumeri
c”dat ainbytes.Maxi mum li
mi ti
supto2000byt
es.
Sy nt
ax: col
umnnamechar( si
ze);
Bydef aultchar acterdatatypehavingoneby t
e.Characterdatat ypeaut omati
call
y
“BlankPadded” .
BlankPadded: Whenev erwear epassinglessnumberofchar acterst hanthespecif
ieddat
atypesi
ze
thenor acleserv eraut
omat i
cal
lyall
ocatesblankspacesaf t
erthev alue.Example:

Varchar2(maxsi
ze):Iti
susedt ostor evar
iabl
elengt halphanumeri
cdatainbytes.Maximum li
mitis
upto4,000by t
es.Whenev erwear eusingv ar
char2()datatypeoracl
eservernotblankpadded.Af
ter
thevaluepassedintothatcolumn.
Oracl
e7.0i nt
roduced“ varchar
2()”datatypepr i
ortooracle7.
0wear eusi ngvar
char2data
type.I
tisalsosameasv archar
2()datatype.Butitwillst
oresupto2000byt
es.
Syntax:col
umnnamev archar2(
maxsi ze)
;

Date:Itisusedtostor
edatesi
noracl
edat
efor
mat
.
Syntax:columnnamedate;
I
nor aclebydefaul
tdatef
ormatisDD-
MON- YY

Dat
e:9/3/15
Dat
aDef i
nit
ionLanguage(
DDL)
:
 Creat
e
 Alt
er
 Drop

MUARLISI
R 2015
13

Cl
assi
fi
cat
ion:
Publ
ic
Truncat
e
Rename( or
ace9i
)

Create:I
tisusedt ocr eatedatabaseobject
sliketables, vi
ews,sequences,
indexes.Cr
eati
nga
table:
Synt ax:
createtabletablename( columnname1dat atype(size),
columnname2dat aty
pe(si
ze)
…..)
;
Exampl e:SQL>cr eatetablef i
rst(
snonumber (
10),namev archar2(10)
);Tovi
ew
structureofthetable:
Synt ax:
desct abl
ename;
Exampl e:SQL>descf ir
st ;
Alter
:Iti
susedt ochangest r
uctur
eoftheexisti
ngt able.

Add:I
tisusedtoaddnumberofcol umnsint
otheexisti
ngt
abl
e.
Synt
ax:Al
tertabl
etablenameadd(col
1datat
ype(si
ze))
;
Exampl
e:SQL>al t
ertablef
ir
staddsalnumber(
10);
SQL>desctable;

Modify
:Itisusedtochangecolumndat aty
peorcolumndataty
pesizeonly.
Synt
ax:alt
ertabl
etablenamemodi f
y(coldatat
ype(
size)
,col
2datat
ype(
size)
);
Example:SQL>alt
ertablefi
rstmodif
ysnodat e;

Drop:I tisusedt oremov ecol umnsf r


om theexisti
ngt abl
e.
Met hod1:I fwewantt odr opasi nglecolumnatat imewithoutusingpar enthesi
s”(
)”t
henwear
eusi
ng
fol
lowi ngsy nt ax:
Altertabl et ablenamedr opcol umncol umnname;
Exampl e: SQL>al t
ert ablef i
rstdropcol umnsal ;
SQL>descf irst ;
Met hod2:I fwewantt odr opsi ngleormul ti
plecolumnswi thusingpar enthesist
henweareusi
ng
fol
lowi ngsy nt ax.
Syntax: altert abl et ablenamedr op(colname1, col
name2, colname3…. )
;
Exampl e: SQL>al t
ert ablef i
rstdrop(sal);
I
mpor tant :
SQL>al tert abl efirstdr opcol umnsno;
Error:cannotdr opal lcolumnsi nat able.
NOTE:I nal l dat abasesy stemswecannotdr opall col
umnsi nat able.
DROP:I ti susedt oremov edat abaseobjectsfrom database.Sy ntax:
dropobj ectty peobj ectname;
1.Dr opt ablet ablename;
2.Dr opv iewv iewname;

MUARLISI
R 2015
14

Cl
assi
fi
cat
ion:
Publ
ic
Dr
opi
ngaTabl
e:

BeforeOracl
e10g:
Syntax:
droptabl
etabl
ename;

Or
acle10g(Enterpr
iseEdi
ti
on)
Sy
ntax:dr
optabletabl
ename;

Geti
tbackfrom recy cl
ebin.
Synt
ax:fl
ashbackt abletabl
enamet obefor
edrop;
Todroppermanent ly:
Synt
ax:droptabletablenamepur ge;
Exampl
e:(droppingat able or
acl e10gEnter
pri
seEdi
ti
on)
SQL>droptablefir
st;
Tabl
edropped.
Geti
tbackthet abl
e:
SQL>fl
ashbackt ablefir
sttobeforedrop;

Testi
ng:
Method1:SQL>descf i
rst
;
Err
or:Obj
ectfi
rstdoesnotexi
st.

Method2:SQL>fl
ashbackt
ablefi
rstt
obef
oredr
op;
Er
ror:obj
ectnoti
nRecycl
ebin.

Dat
e:10/
3/15

RECYCLEBIN:Or
acle10gint
roducedrecycl
ebinwhichisusedtostor
edr
oppedt
abl
es.Recy
clebinisa
readonl
ytabl
ewheneverweareinst
all
ingoracl
ethenautomati
cal
lyso
MUARLISIR 2015
15

Cl
assi
fi
cat
ion:
Publ
ic
manyr
eadonl
ytabl
esar
ecr
eat
ed.Theser
eadonl
ytabl
esar
eal
socal
l
edas“Dat
aDi
cti
onar
ies”
.

I
nor acle, wecanal sodr optablesfrom r
ecycl
ebi
nusi
ng“
pur
ge”command.
ToDr oppar ti
culart ablef r
om Recy cl
ebin:
Syntax: purget ablet ablename;
Exampl e: SQL>cr eatetabl efir
st(
snonumber (
10)
);
SQL>dr opt ablefirst;
SQL>descr ecyclebi n;
SQL>sel ectoriginal_namef rom recycl
ebi
n;
Original_name
-
---
---
----
--
---
--
--
Fi
r st
SQL>pur get ablef i
rst;
Testing:
SQL>sel ectoriginal_namef rom recycl
ebi
n;
Nor owssel ected;

ToDr opal ltablesf r


om Recy cl
ebin:
Syntax:SQL>pur gerecy cl
ebi
n;
Exampl e: SQL>cr eatet abl
efir
st(
snonumber (
10)
);
SQL>cr eat etablesecond( snonumber (10))
;
SQL>dr opt ablefir
st;
SQL>dr opt ablesecond;
SQL>descr ecyclebin;
SQL>sel ectorigi
nal_ namef r
om recy
clebin;
Origi
nal _name
-
---
--
---
--
-----
--
---
-
First
Second
SQL>pur ger ecyclebin;

Test
ing:
SQL>selector
igi
nal
_namef
rom r
ecy
clebi
n;
MUARLISI
R 2015
16

Cl
assi
fi
cat
ion:
Publ
ic
Nor
owssel
ect
ed

Truncat e:Oracle7.0i ntr


oducedt r
uncat
ecommand, whenev
erwear
eusi
ng“
truncat
e”
commandt otaldataper manentlydel
etedf
rom t
abl
e.
Syntax:truncatetablet abl
ename;
Exampl e:createtablefirstasselect*fr
om emp;
SQL>sel ect*from f i
rst;
SQL>t runcatetablefirst;
Testing:SQL>sel ect*f rom fi
rst
;
Norowssel ected.
SQL>descf ir
st;

Rename:I ti
susedt orenameat abl
eandrenami
ngacol
umnal
so.
RenamingaTabl e:
Synt
ax:renameol dtabl
enamet onewtabl
ename;
Example:renamef i
rstt
olast;

Renami ngaCol umn:( oracle9i)


Syntax:al
tertabletablenamer enamecol
umnoldcol
umnnametonewcol
umnname;
Example:SQL>al tertableempr enamecol
umnempnotosno;SQL>
sel
ect*f r
om emp;
Note:Inalldatabasesy stemsbydefaul
tal
lDDLcommandsareautomat
ical
l
ycommit
ted.

DATAMANI PULATI ONLANGUAGE( DML):


I
nser t
Updat e
Delete
Mer ge(oracle9i)
Thesecommandsar eusedt omani pulatedatainatabl
e.
1)Insert:I
ti susedt oinsertdataintoatable.
Met hod1:Insertintotablenamev alues(val
ue1,val
ue2,v
alue3….
.)
;
Exampl e:SQL>cr eatet abl
ef i
rst
(snonumber (10),
namev ar
char
(20)
);

I
nser t
ingdataintot able:
SQL>i nserti
ntofirstv alues(1,„
abc‟ );
SQL>i nserti
ntofirstv alues(2,„
sachi n‟)
;
SQL>sel ect*from f ir
st;
Sno name
-
---
--
---
-- ---
--
-----
--
-
1 abc
2 sachi n
Method2:( usi
ngsubst ituti
onaloper ator“&”
)
Syntax:inser
tintot ablenamev alues(&col1,
&col2,&col
3……)
;
Exampl e:SQL>inser tintof i
rstvalues(&sno,„&name‟);
MUARLISI R 2015
17

Cl
assi
fi
cat
ion:
Publ
ic
Ent
erval
ueforsno:
3
Ent
erval
ueforname:xyz
SQL>/
Ent
erval
ueforsno:
4
Ent
erval
ueforname:sachi
n
SQL>sel
ect*fr
om fi
rst
;

Dat
e:11/
3/15

Method3:(skippingcolumns)
Synt
ax:insertint
ot abl
ename(columnname1,col
umnname2,
…..
)val
ues(
val
ue1,
val
ue2,
…);
Example:SQL>i nserti
ntofi
rst
(name)val
ues(
„www‟);
SQL>select*from fir
st;

2)Updat e:I
tisusedt ochangedat awithinatabl
e.
Syntax:updatet ablenamesetcol umnname=newv al
uewher ecolumnname=ol
dval
ue;
Example: SQL>updat eempsetsal =1000wher eename=‟ SMI TH‟;SQL>
sel
ect*f rom f
irst;
Note:Inalldatabasei fwewantt oi
nsertdataint
opar t
icularcel
lthenwemustuseupdat
ecommand.
Example: SQL>al tertabl
ef i
rstaddaddressvarchar2(
10) ;
SQL>updat efirstsetaddr ess=‟mumbai ‟wherename=‟ sachin‟
;
SQL>sel ect*from f i
rst;

Out
put
:sno name address
-
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
1 abc
2 sachin Mumbai
3 xyz
4 zzz
Example:
SQL>updatefir
stsetaddress=nul
lwher
ename=‟
sachi
n‟;
SQL>
sel
ect*fr
om f
ir
st;

Delete:Iti
susedt odeleteparti
cularrowsorall
rowsf
rom at
abl
e;Sy
ntax:
Delet
efrom tabl
ename;
Delet
efrom tabl
enamewher econditi
on;
Fi
rstcommandi stodeleteallrows
Secondcommandi stodeleteparti
cularrows.
Exampl e:SQL>deletefrom fi
rst;
Rowsdel eted.
SQL>r oll
back;
SQL>sel ect*fr
om first
;

MUARLISI
R 2015
18

Cl
assi
fi
cat
ion:
Publ
ic
Diff
erencebetween„ del
ete‟and„truncate‟:
Whenev erwear eusing„delet
ef rom tablename‟or„ t
runcatet abl
et abl
ename‟thenautomati
cal
lytotal
dataisdelet
ed.Whenev erwear eusing„ del
etefr
om tablename‟t hendeleteddat
aautomati
call
yst
oredin
abuf f
er.Wecangeti tback,thisdeleteddat ausi
ng“ roll
back”.Whenev erweareusing„tr
uncat
et abl
e
tabl
ename‟t hentotaldatapermanent l
ydel et
ed.Becauset runcateisanDDLcommand.That ‟swhywe
cannotgetitbackthisdatausi
ng“ rol
lback”.

DATARETRIVALLANGUAGE(DRL)(OR)DATAQUERYLANGUAGE(DQL):-
>Sel
ect
I
nrelat
ional
dat
abaseswecanr
etr
iev
edatafromt
abl
eusi
ngsel
ectst
atement
.

nSy
ntax: sel
ectcol
1,col
2,….From t
abl
enamewher
econdi
ti
on
groupbycolumnname
hav i
ngcondit
ion
orderbycolumnname[ asc/
desc]
;

Sel
ectal
lcol
sandallr
ows.
Sel
ectal
lcol
sandparti
cul
arr
ows.
Sel
ectpar
ti
cul
arcol
sandallr
ows.
Sel
ectpar
ti
cul
arcol
sandparti
cul
arr
ows.

Dat e:12/ 3/15


Creat i
nganewt ablefrom anot hertable:
Synt ax:cr eatet ablenewt ablenameassel ect*from existi
ngtabl
ename;
Exampl e:SQL>cr eatetablet estasselect*f rom emp; SQL>
select*f rom test ;
Not e:I nal l
dat abasesy stemswhenev erwear ecopyingat ablef
rom anot
hert
abl
econstrai
ntsar
enev
er
copi ed.( Primar ytable,Forei
gnkey ,
…..)
;
Creat inganewt abl
ef r
om exi sti
ngt ablewi t
houtcopy ingdata:
Synt ax:cr eatet ablenewt ablenameassel ect*from existi
ngtabl
enamewherefal
secondi
ti
on;
Exampl e:SQL>cr eatetablet est1assel ect*from empwher e1=2;
Test ing:SQL>sel ect*from t est1;
Nor owssel ected.
SQL>desct est1;
Oper atorsUsedi n“Sel
ect ”statement :

Art
hemat icoperator(
+,-
,*
,/)
Relati
onaloperator(
=,<,
<=,
>,>=,
[
<>or
!=]
notequal
).
Logicaloperat
or( AND,OR,NOT)
MUARLISIR 2015
19

Cl
assi
fi
cat
ion:
Publ
ic
4.Speci
aloper
ator
.

Ari
thmeti
coper at
orisusedf or“select
”(eg:selectcol
umn1,column2,
…)
Rel
ati
onalandLogi calandSpecialoperatorsareusedfor“where”(
eg:wher
econdi
ti
on)Wecanal
so
useari
thmeti
coper atorsin“where”conditi
ons.
 Ari
thmet i
coper atorsareusedinnumber ,dat
adatat
ypecolumn.
writ
eaquer ytodisplayename, sal,
annsalfrom emptable;
Ans:SQL>selectename, sal,sal
*12annsal fr
om emp;

ENAME--
-- SAL ANNSAL
-
--
--
-- -
--
--
--
--
-- -
--
--
--
---
--
--
--
--
--
SMITH 700 8400

wri
teaqueryt
odispl
ayt
heempl oyeesexceptj
obascl
erkfr
om empt
abl
e.
Ans:
select*f
rom empwher
ejob<>‟CLERK‟;(orj
ob!
=„CLERK‟)

Wri
teaquerytodi
spl
aytheemploy
eeswhoar eget
ti
ngmor
ethan2000sal
aryf
rom empt
abl
e?
Ans:
SQL>select*fr
om empwheresal>2000;

Example:SQL>select*f
rom empwherej
ob=‟CLERK‟andsal>2000;
Note:I
ndatabasesifwewanttoret
ri
evemult
ipl
evalueswithi
nasinglecol
umnt
henwemustuse“
OR”
operat
or.
Example:SQL>select*f
rom empwherej
ob=‟CLERK‟orjob=‟SALESMAN‟;

wri
teaquerytodi
spl
aytheempl
oyeeswhoarebel
ongstot
hedepart
mentnumbers20,
50,
70,
90?
Ans:
SQL>select*fr
om empwheredept
no=20ordept
no=50ordept
no=70ordept
no=90;

SQL>sel
ect*f
rom empwher
esal
>2000andsal
<5000;

Specialoperat
ors:
1)„I
n‟opposite„noti
n‟
2)„between‟opposit
e„notbetween‟
3)„i
snull‟opposit
e„isnotnul
l

4)„l
ike‟opposi
te„notli
ke‟

In:Itisusedtopi ckthev al
uesonebyonef r
om li
stofvalues.„In‟operat
orperf
ormanceisveryhi
gh
compar edto„OR‟oper ator
.Ifwewantt oretr
iev
emul t
ipl
ev al
uesi nasingl
e
columnt henwear eusing„IN‟operator
sinplaceof„OR‟oper at
orbecause„ I
N‟oper
atorper
for
mance
ishigh.
Syntax:select*f
rom tablenamewher ecolumnnamei n(
li
stofvalues);
Columnnamebel ongst oanydat aty
pei spossibl
e.
Exampl e:SQL>select*from empwher edeptnoin(20,
30,
50,70,90);
MUARLISI R 2015
20

Cl
assi
fi
cat
ion:
Publ
ic
Date:13/ 3/15
Eg:SQL>sel ect*f r
om empwher eenamei n(„SMITH‟ ,
‟FORD);
Note:Inal ldatebasesy stemswhenev erwear eusi ngmulti
plerowsubqueriest henwemustuse“i
n”
operat
or .
Eg:select*f rom empwher edeptnonoti n(10,20,null
);
Note:Inal lrel
ationaldatabases“ notin”oper atordoesn‟twor kwit
h“null
”values.
Null
:Nul lisanundef i
ned, unavai
labl
e, unknownv alue.I
tisnotsameas“ zer
o” .Anyarit
hmeti
coper
ati
ons
perf
ormedonnul lval
uesagai nitbecomes“ null”
.
Eg:null+50=>nul l
.
Wr i
teaquer yt odispl
ayename, sal,comm, sal+comm oft heemploy
eeSMI THf rom empt
abl
e.
Ans:SQL>sel ectename, sal,comm, sal+comm f rom empwher eename=”SMI TH” ;

o/
p:enamesal comm.Sal+comm -
--
--
--
--
---
--
--
---
--
--
--
--
-
--
--
--
--
--
--
--
--SMITH1100null
null

Toov ercomet hisproblem or acleprov


ided“NVL( )
”functi
on.
NVL( )
:NVL( )isapr edefinedf unct
ionwhichisusedt orepl
aceorsubst
it
uteuserdef
inedval
uei
npl
aceof
“null
”.
Syntax:NVL( exp1,exp2);
Hereexp1,exp2mustbel ongst osamedat atype.Ifexp1isnullt
henitret
urnsexp2.
Otherwiseitreturnsexp1.
Eg:1)NVL( null,
30)->30.
2)NVL( 10,
20)- >10.
Soluti
on:selectename, sal,comm, sal+NVL(comm, 0)from empwhereename= SMI TH”
;

ENAME SAL COMM SAL+COMM


-
--
--
--
---
--
--
--
---
--
--
--
--
----
--
--
--
--
--
--
--
-
SMITH 1100 Null 1100

Sal
+nvl
(comm. ,
0)
1100+nvl
(1100,
0)
1100+0
1100

NVL2( )
:Or acl
e9i int roducedNVL2( )functi
on.Thi
sfuncti
onacceptsthr
eepar
amet
ers.
Syntax:NVL2( exp1, exp2,exp3).
Hereifexp1i snull,t henitretur
nsexp3.Ot herwi
seitr
eturnsexp2.
Eg:SQL>sel ectnv l2( null
,
10,20)from dual
;
20
SQL>sel ectnvl2(30, 40,50)from dual
;
40
Q)Updat eempl oyeecommi ssi
onasf oll
owsusingnvl
2()from emptabl
e;
MUARLISI R 2015
21

Cl
assi
fi
cat
ion:
Publ
ic
I
fcomm i snul
lthenupdatecomm.->500
I
fcomm i snotnull
thenupdatecomm- >500
Ans:SQL>updateempsetcomm=nv l
2(comm, comm+500,
500)
;
SQL>updateempsetcomm=nv l2(
comm, comm+500,
500);
SQL>select*fr
om emp;

Between:Thisoper
atorisusedtoret
ri
ever
angeofval
ues.Thi
soperat
ori
salsocal
las
Betweem…. .Andoper
ator
.
Syntax:Sel
ect*fr
om tabl
enamewher ecol
umnnamebetweenlowval
ueandhi
ghval
ue.
Eg:select*fr
om empwher esalbet
ween2000and5000;

Dat
e:14/
3/15

Whil
eusi
ng“DATE”:
SQL>sel
ect*f
rom empwher
ehi
redat
ebet
ween‟
01-
jan-
1981‟and‟
01-
jan-
1982‟
;

I
snull,i
snotnull
:Theset wooperat or
susedin„where”condi
tiononly
.Thesetwooper
ator
sareusedt
o
testweatheracolumnhav ingnul
lvaluesornot.
Syntax:select*f
rom t
ablenamewher ecol umnnameisnull;
Syntax:select*f
rom t
ablenamewher ecol umnnameisnotnull;
Q)wr i
teaquer yt
odisplaytheemploy eeswhoar enotget
ti
ngcommi ssi
onfr
om emptabl
e.Ans:
SQL>
select*from empwherecomm i snull;

wri
teaqueryt
odi
spl
aytheempl
oyeeswhoar
eget
ti
ngcommi
ssi
onf
rom empt
abl
e?Ans:
SQL>
sel
ect*f
rom empwher
ecomm isnotnul
l
;

Li
ke:Iti
susedtosearchstr
ingsbasedoncharact
erpat
ter
n.“
Like”oper
atorper
for
mancei
sveryhi
gh
comparetosearchi
ngfuncti
ons.Inalldat
abasesalongwit
hli
keoper at
orwear eusi
ng2wi l
dcard
char
cter
s.

-
>groupofcharact
ersifwantt
omat
chorst
ri
ng_-
>
si
ngl
echaract
ertomat ch.

Sy
ntax:sel
ect*f
rom t
ablenamewherecol
umnnameli
ke„
character
pat
ter
n‟;
wri
teaqueryt
odispl
aytheemploy
eeswhoseenamest
artwith“M”fr
om empt
abl
eusi
ngl
i
keoper
ator
.

Ans:
SQL>sel
ect*f
rom empwher
eenamel
i
ke„
M‟;
MUARLISI
R 2015
22

Cl
assi
fi
cat
ion:
Publ
ic
MARTI N
MI LLER
writeaquerytodi
spl
aytheempl
oyeeswher eenamesecondlet
terwil
lbe„L‟f
rom emptabl
eusing
„l
ike‟operator
?
Ans: SQL>select*fr
om empwhereenamelike„__L%‟;
ALLEN
CLARK
BLAKE
writeaquerytodi
spl
aytheempl
oyeeswhoar ejoi
ningi
nthemont hDecemberfr
om theemptable
usingl i
keoperat
or.
Ans: SQL>select*fr
om empwherehi
redat
el i
ke„___D%‟;(
or)„
%DEC%” ;

writ
eaquerytodi
spl
aytheempl
oyeeswhoarej
oini
ngint
hey
ear“
81”f
rom empt
abl
eusi
ngl
i
ke
oper
ator?
Ans:SQL>sel
ect*fr
om empwhereemptabl
eli
ke„%81‟;

“Escape”f unct ionusedi nl ikeoper ator:


Whenev erwi l
dcar dchar act ersavailableinchar acterdat
at henwear et ry
ingt oretri
ev ethedatausingli
ke
oper atorthendat abaseser v er
st r
eat edthesewi ldcardchar actersasspeci alcharacterstoovercomet hi
s
probl em ansi /isoSQLpr ovidedaspeci alf uncti
on“ Escape”al ongwi t
h„ li
ke‟oper ator.Whichisusedt o
escapespeci al char actersandal sot hisfunct i
ont r
eatedas_ ,%assamemeani ngas_ ,
%.
Synt ax:sel ect*f rom t ablenamewher ecolumnnamel i
ke„ characterpattern‟escape„ escapechar act
er‟
;
Not e:Escapechar actermustbeansi nglechar acterhav inglengt h„1‟wi t
hinchar acterpatt
ernwemust
useescapechar act erbeforewi ldcar dcharact er
.
Eg: SQL>i nser tintoemp( empno, ename)v alues(1,
‟S_MI TH‟ );SQL>
select*f rom emp;
wr i
teaquer ytodi spl
ayt heempl oy eeswhoseenamest ar twith„S_
‟f r
om empt ableusi ng„l
i
ke‟
oper ator?
Ans: SQL>sel ect*f rom empwher eenamel ike„S_%‟ ;
SMI TH
SCOTT
S_MI TH
Solut i
on: SQL>sel ect*f r
om empwher eenamel ike„S?_%‟escape‟ ?‟
;
S_MI TH
Eg: i
nser tintoemp( empno, ename)v alues(2,‟S__MITH‟);
SQL>sel ect*f rom emp;
Solut i
on: SQL>sel ect*f r
om empwher eenamel ike„S?_?_%‟escape‟ ? ‟
;
S__MI TH

Concat
enati
onOper at
or(|
|doubl
epipe)
:Iti
snotaspeci
aloper
atorr
arel
yusedi
n

SQL”andregularl
yusedin“PL/SQL”
.Ifwewanttodi
spl
aycolumndataalongwi
thl
it
eral
str
ingst
henwe
mustuseconcatenat
ionoperat
or.
MUARLISIR 2015
23

Cl
assi
fi
cat
ion:
Publ
ic
Eg:
sel
ect„myemployeenamesare‟
||enamefrom emp;
I
fwewanttodispl
ayourownspaceinbetweenthecol
umnst
henal
sowecanuseconcat
enat
ionoper
ator
.
Eg:
sel
ectename||
‟ „
||
salfr
om emp;

Date:16/3/ 15
Functions:Funct i
onsar eusedtosolv
eparticul
artaskandal
sofuncti
onsmustr
etur
nav
alue.Or
acl
ehav
e
twot ypesoffunct ions.
Predefi
nedf unctions
Userdefinedf unct i
ons
Predefi
nedf unct ions:t
her
eare4types.
Numberf unction
Characterfunct i
on
Datefunct i
on
Groupf unction(or
)Aggr
egatefunct
ion
Numberf unct i
on:Thesefunct
ionsoperateover“number
”data.

Abs():Itisusedt oconv er
tnegat i
vev al
uesint
opositi
veval
ues.
Eg:SQL>sel ectabs( -
50)fr
om dual ;50
Dual()
:Dual i
sapr edef i
nedvirt
ual t
ablewhichcontai
nsonlyonerowandonecol
umnDual
tabl
eisused
totestpredefined, userdefi
nedf uncti
onsfuncti
onali
ty.
Examplef ortestingpr edef
inedfunct i
ons:SQL>
sel
ectnv l(
null
,30)f rom dual;
30
SQL>sel ectnv l
(20,30)from dual;20
SQL>sel ect*f r
om dual ;

Note:I
noracl
ebydefaul
tdual
tabl
ecol
umndat
aty
pei
svar
char
2()
.
Eg:
select*fr
om dual
;

General
l
y,thi
stablei
salsousedtoperf
orm mathemati
caloper
ati
ons.Eg:
SQL>
sel
ect10+50f r
om dual
;
60
Eg:SQL>selectename,comm,sal,
abs(comm-sal)f
rom empwherecomm isnotnul
l
;

Mod(
m,n)
:Itwi
l
lgi
vesr
emai
nderaf
ter„
m‟di
vi
dedby„
n‟.

Eg:
SQL>sel
ectmod(
10,
5)f
rom dual
;0

MUARLISI
R 2015
24

Cl
assi
fi
cat
ion:
Publ
ic
Round( m,n) :Itr oundsgi v enf loatedv aluednumber„ m‟basedon„ n‟.
Eg:SQL>sel ectr ound( 1.8)f rom dual ; 2
SQL>sel ectr ound( 1.23456, 3)f r
om dual ;1.235
Note:Roundal way schecksr emai ningnumberi fremainingnumberi sabove50%t henoneaddedt othe
roundednumber .
Eg:SQL>sel ectr ound( 1285. 456, -1)f rom dual ;1290
Execut ion:
Step1: 1280- >5i sr eplacewi th0.Outof10, 5isabov e50%( >=)
Step2: 1280
+1
--
--
--
--
- -
----
-
1290
Eg:sel ectename, sal ,round( sal ,
-1)f rom emp;
Eg:sel ectename, sal ,round( sal /22) ,round( sal/22,
1),round(sal
/22,2)f
rom emp;
Trunc( m,n) :Itt runcat esgi venf l
oat edv aluesnumber„ m‟basedon„ n‟
.Thi
sfunctiondoesn‟
tcheck
remai ningnumberi sabov e50%orbel ow50%.
Eg:SQL>sel ectt runk( 1.8)f rom dual ;
Eg:SQL>sel ectt runk( 1.23456, 3)f rom dual ;1.
234
Greatest (exp1, exp2, ….expn) , Least (exp1, exp2,….expn):
Greatestr et ur nsmaxi mum v alueamonggi venexpressions.WhereasLeastr et
urnsminimum value
amonggi venexpr essions.
Eg:SQL>sel ectgr eat est( 3,5,8, 9)fr om dual ;9
SQL>sel ectename, sal,comm, great est (sal,
comm) from empwher ecomm isnotnull
;SQL>select
max( sal)f r
om emp;
6600

Dat
e:18/
3/15

Ceil
()andFl oor():Theset wofuncti
onsalway sreturni
nteger
.Cei
l(
)retur
nsnear
estgr
eat
esti
nteger
whereasf l
oor (
)r etur
nsnear estl
owestinteger.
Eg:sel
ectcei l
(1.3)from dual;2
Eg:sel
ectfloor(1.9)from dual;1
CHARCTERFUNCTI ONS:
Upper():I
tisusedt oconv er
tastri
ngorcol umnv aluesint
o“uppercase“.
Eg:sel
ectupper („abc‟ )f
rom dual;
ABC
Forcolumn: SQL>sel ectupper(
ename)from dual;
MUARLISI R 2015
25

Cl
assi
fi
cat
ion:
Publ
ic
Lower ():
Eg: selectlower (ename)f r
om emp; Updat i
ngor
modi fyingdat awi thintable:SQL>updat eempset
ename=l ower (ename) ;
Init
cap( ):Itreturnsf i
rstlett
eriscapi talandal lr
emainingl
ettersaresmall
.
Eg: SQL>sel ectinitcap(ename)f r
om emp;
Eg: SQL>sel ectinitcap(„abcdef ‟
)from emp; AbCd
Ef
Lengt h():Itreturnsnumberdat atypet hatis.,i
tretur
nstotall
engthofthestri
ngincl
udi
ngspaces.
Eg: selectlengt h(„
AB_ CD‟ )fr
om dual ;
5
Subst r():I
twi l
l extr
actpor ti
onoft hest r
ingwi t
hingivenst
ringbasedonlasttwoparameter
s.
Eg:selectsubst r
(„ABCDEF‟ ,
2,3)from dual ;
BCD
SQL>sel ectsubst r(„
ABCDEF‟ ,
-2,3)from dual ;
EF
SQL>sel ectsubst r(„
ABCDEF‟ ,
-4)from dual ;
CDEF
Syntax:subst r(columnname( or)„stri
ngname‟ ,st
art
ingposit
ion,no.ofchar
actersposi
ti
on)
;
Star
tingposi t
ion->canbe+v eor–v e
Star
tingposi t
ionandno.ofchar act ersposition->mustbenumber s

writ
eaquer ytodisplaytheemployeeswhoseenamesecondl et
terwouldbe“ LA”f r
om empt abl
eusing
substr
ingfunction?
And:SQL>sel ect*from empwher esubstr
(ename,
2,
2)=‟
LA‟;
BLAKE
CLARK
Note:Inalldatabasesy stemswear enotall
owedtousegroupfuncti
onsi nwhereclausebutwear eall
owed
tousenumberf unct
ions, char
acterf
uncti
ons,dat
efunct
ionsinwhereclause.Eg:select*from empwher e
sal
=max( sal)
;
Err
or:groupfunctionisnotal l
owedhere.
writ
eaquer ytodisplaytheemployeewhoseemployeeslengt
his5f rom empt able.Ans:SQL>
sel
ect*f r
om empwher elengt
h(ename)=5;

Inst
r()
:instr(
)al
way sr
eturnsnumberdatatypet
hati
sitr
etur
nsposi
ti
onoft
hedel
i
mit
er,
posi
ti
onoft
he
charact
er,positi
onofthestri
ngwithingiv
enstr
ing.
Eg:SQL>sel ecti
nst
r(„
ABC* D‟,
‟*‟
)from dual
;

Date:19/3/
15
Eg:SQL>selectinst
r(„
ABCDEFGHCDKMNHCDJL‟,
‟CD‟,
-5,
2)f
rom dual
;3
SQL>selectinst
r(„
ABCDEFGHCDKMNHCDJL‟,
‟CD‟,
-4,
2)fr
om dual;
MUARLISIR 2015
26

Cl
assi
fi
cat
ion:
Publ
ic
9
Syntax:inst
r(col
umnname(or)‟st
ri
ngname‟,„st
r‟,searchi
ngposi
ti
on,No.ofoccurr
encesfrom searching
posi
tion);
Searchingpositi
on->+veor–ve
SearchingandNo.ofoccurrences->mustbenumber s.
Alwaysi nstr
ingretur
nspositi
onbasedonlasttwopar ameter
sbutoracl
eser
vercountsno.ofcharacters
l
eftsidefir
stpositi
ononwards.

Lpad():I
twillfi
ll
sremai ningspaceswithspeci
fi
edcharact
eronthelef
tsi
deofthegiv
enstr
ing.Hereal
ways
second paramet erreturnst otall
ength ofthestri
ng.And al
so thi
rd par
ameterisan opti
onal
.Sy
ntax:
Lpad(col
umnname( or)„ str
ingname‟,t
otall
ength,
„fi
l
ledchar
act
er‟)
;
Totall
ength- >number

Eg:SQL>selectl
pad(„ABCD‟,10,‟
#‟)fr
om dual
;
######ABCD
SQL>selectl
pad(„ABC‟,
5)from dual;
(
space)
(space)ABC
SQL>selectl
pad(„ABC‟,
2,‟
*‟)from dual
;
AB

Rpad()
:
Eg:SQL>selectrpad(„
ABCD‟,
10,‟
#‟)
from dual
;
ABCD######
SQL>selectrpad(ENAME,50,
‟-
„)
||
sal
from emp;

Lt
rim:Itremovi
esspeci
fi
edcharacteront
heleftsideoft
hegivenst
ri
ng.
Syntax:Ltr
im(
col
umnname(or)
‟str
ingname‟,
{ setofchar
act
ers})
;

Eg:SQL>sel ectl
tr
im(
„SSMISSTHSS‟ ,
‟S‟)f
rom dual
;
MISSTHSS
SQL>sel ectj
ob,l
tr
im(
job,
‟CSM‟ )from emp;
JOB LTRIM(JOB)
-
---
---
--
--
--
---
- ---
--
--
--
----
--
--
--
---
--
-
CLERK LERK
SALESMAN ALESMAN
MANAGER ANAGER

Rtr
im:
Eg:SQL>sel ectrt
ri
m( „
SSMISSTHSS‟ ,
‟S‟)from dual
;
SSMI SSTH
Tri
m( ):Oracl
e8i i
ntr
oducedtr
imf uncti
oni tisusedtor
emovel
eftandr
ightsi
despeci
fi
edchar
act
ersand
al
soi tisusedtoremov el
eadingandtraili
ngspaces.
Syntax:tr
im(„char
acter‟f
rom „st
ri
ngname‟ );
MUARLISI R 2015
27

Cl
assi
fi
cat
ion:
Publ
ic
Eg:SQL>sel ecttri
m(„S‟fr
om „SSMISSTHSS‟ )
from dual;
MISSTH
Thisfuncti
onal sobehavesli
kealtr
im,rtr
im basedonl eadi
ngandt
rai
l
ingcl
aused.Eg:
sel
ect
tr
im(l
eading„ s‟fr
om „SSMISSTHSS‟ )f
rom dual;
SSMISSTH
Eg:selectl
ength(tri
m(„welcome„))
from dual;7

Tr
ansl
ate()andRepl
ace()
:
Tr
ansl
ate()i
susedtorepl
aceschar
act
erbychar
act
erwher
easr
epl
ace(
)isusedt
orepl
aceschar
act
erby
st
ri
ng(or)st
ri
ngbystr
ing.

Eg:
sel
ectt
ransl
ate(
„i
ndi
a‟,
‟i
n‟,
‟xy
‟),
repl
ace(
„i
ndi
a‟,
‟i
n‟,
‟xy
‟)f
rom dual
;

Tr
anslat
e Repl
ace
Xydxa xydi
a

Syntax:tr
ansl ate(
„str1‟,
‟str
2‟,‟
st r
3‟….);
Eg:selecttranslate(„
ABCDEF‟ ,
‟FEDCBA‟ ,123456);
654321
Eg:selectreplace(„ABC‟ ,
‟„,
‟india‟)f
rom dual;
Aindi
aBindiaC
Eg:selectj
ob, repl
ace( j
ob,„SALESMAN‟ ,‟MARKETING‟ )f
rom emp;
Note:Inreplacef unctionifwear enotspecifyi
ngthir
dparameterspeci
fi
edchar
act
erper
manent
lyr
emov
ed
fr
om thest ring.
Eg:selectreplace(„SSMI SSTHSS‟ ,
‟S‟)f
rom dual;
MI TH

Date:20/ 3/15
I
fy ouwantt ocountnumberoft i
mespar t
icularcharacteroccur
swi t
hinagi
venstr
ingt
henalsowear e
usingreplacef unctionalongwithlengt
hf unct i
on.
Wri
teaquer ytocountnumberoft i
mest hatparti
cular„I
‟occurr
edwithi
ngiv
enstri
ng„i
ndia‟usi
ng
replacefunction?
Ans: SQL>sel ectlength(„i
ndi
a‟)
-lengt
h(replace(„i
ndi
a‟ ,
‟I
‟))f
rom dual
;
2
Concat (
):Itisusedt oconcat
enat egi
vent wost ri
ngs.
Eg: sel
ectconcat („wel‟,
‟come‟)
from dual;
Wel come

DATEf uncti
ons:Inor
acl
ebydef
aul
tdat
efor
mati
sDD-
MON-YY.Or
acl
ehav
ingf
oll
owi
ngdat
efunct
ions.
Sysdate
Add_mont hs(
)
Last_day(
)
MUARLISI R 2015
28

Cl
assi
fi
cat
ion:
Publ
ic
Next
_day()
Months_
between(
)

Sy sdat e:Itretur nscur r


entdat eoft hesy stem int heor acl
edatef ormatSQL>
selectsy sdat efrom dual ;
20-MAR- 15
Add_ mont hs():Iti susedt oaddorsubt r
actnumberofmont hstothespeci fi
eddate
basedonsecondpar amet er .
Synt ax:add_ mont hs( dat e, number );
Number -
>canbeposi ti
veornegat ive.
Eg: SQL>sel ectadd_ mont hs( sy sdat e,1)from dual; 20- Apr-
15
SQL>sel ectadd_ mont hs( sy sdat e,-
1)f r
om dual ;20- FEB
-15
Last _day ():Itret urnsl astdat eoft hegi venmont hsbasedont hepasseddat e.Thisfuncti
onal
ways
accept sonepar amet er .
Synt ax:last _day (dat e);
Eg: SQL>sel ectlast _ day( sy sdat e) f
rom dual ;
31-Mar -
15
4)Next _day ():Itret urnsnextoccur r encedayf rom t hespeci fi
eddat ebasedonsecondpar amet
er.
Synt ax:next _ day (
dat e,
‟day ‟);
Eg: selectnext _day (sy sdat e, ‟
monday ‟ )
from dual ;
23-
MAR- 15
Mont hs_ between( ):Thesef unct ional way sretur ns“ number”datat ype.i.
e.,
itret
urnsnumberofmonths
bet weent wospeci fieddat es.
Synt ax:mont hs_bet ween( dat e1, date2)
Heredat e1i smor et handat e2ot herwi set hisfuncti
onr eturns“negat
ive”sign.Eg:SQL>select
ename, round( mont hs_ bet ween( sy sdat e,
hiredate))
from emp;

DATEar i
thmetic:
Date+number
Date–number
Date1+date2
Date1–dat e2
Eg:SQL>selectsysdat e+1f r
om dual;
SQL>selectsysdate-1f rom dual ;
SQL>selectsysdate-sy sdatef r
om dual;
0
wri
teaquer ytodi splayf i
rstdateofthecurrentmont husi
ngpredef
ineddat
efunct
ionssy
sdat
e,
add_months()
,last_dat e(
)f uncti
ons.
Ans:SQL>selectlast_ day((add_mont hs(
sysdat
e,-1)
))+1from dual
;
OR
SQL>selectadd_mont hs(last_day(sy
sdate),
-
1)+1f r
om dual;
MUARLISIR 2015
29

Cl
assi
fi
cat
ion:
Publ
ic
01-
MAR-
15

DATECONVERSI ONFUNCTIONS:
Oracl
eprov i
dedt
wodat
econver
sionf
unct
ion.Theyar
e:
To_char(
)
To_date(
)

Dat
e:23/
3/15

to_char()
:Itisusedt oconvertdat
etimeintocharact
ertypei.
e.,
itconv
ert
sdat
ety
pei
ntodat
est
ri
ng.
Eg:SQL>sel ectto_char(sy
sdate,
‟dd/mm/ yy
‟)f
rom dual;
23/03/15
Note:Basicall
y“ t
o_char”charact
erformatsarecasesensit
ivefor
mat s.
Eg:SQL>sel ectto_char(sy
sdate,
‟DAY‟)fr
om dual
;
MONDAY
Day->Monday (lowercaselett
ers)
DAY
DY
MONTH
MON
YEAR
RETURNSCHARACTERASOUTPUT
D
DD
DDD
MM
YY
YYYY
HH
MI
SS
RETURNSNUMBERASOUTPUT
Eg:SQL>sel ectto_char(sy
sdate,
‟DY‟)f
rom dual
;MON

Eg:SQL>selectt
o_char(sysdat
e,‟D‟)fr
om dual;
2
D->dayoft
heweek( sun-1,mon-
2,tue-3,
….sat-
7)
DD->dayofthemont h
DDD->dayoftheyear(t
ellshowmanyday scomplet
ed)
th th r d
DDTH->usedasdat ewit h„r
d‟or„ t
h‟(eg:5 19 23 )
Eg:SQL>selectt
o_char(sysdat
e,‟
DDSPTH‟ ) f
rom dual
;
Twentythi
rd
MUARLISIR 2015
30

Cl
assi
fi
cat
ion:
Publ
ic
SP->spel
lout
Eg:SQL>selectt
o_char
(sysdat
e,‟
MON‟)from dual
;
MAR
Eg:SQL>selectt
o_char
(sysdat
e,‟
HH:MI:
SS‟)fr
om dual;
09:
51:42
Bydefaul
t12-hour
sformat
toconver
tinto24-
hoursformatwehaveto“ HH24:
MI:SS”(
24-
hour
sfor
mat
)

SQL>selectt
o_char(
‟15-
JUN-05‟
,‟
15-
JUNE-
05‟)f
rom dual;
Err
or:i
nvali
dnumber
Note:wheneverweareusingto_
char
()al
waysf
ir
stpar
amet ermustbeor
acl
e“dat
e”t
ypeot
her
wiseor
acl
e
ser
verretur
nsanerror.

to_dat e( )
:Itisusedt oconv ertdatestr
ingintooracl
e“ date”t
ype(or
acledateformat)Eg:
SQL>
sel
ectt o_ date(‟27/JUNE/ 05‟)f rom dual;
27-
JUN- 05
Eg:SQL>sel ectto_date(„27/06/ 05‟)fr
om dual;
Err
or:inv alidmont h(or )notav al i
dmont h
Whenev erar eusi ngt o_date()passedpar ameterretur
nv al
uesmat chwi t
ht hedefaul
tdatefor
matr etur
n
val
ues.Ot herwiseor acleser verr et
urnsaner ror.Toov ercomet hisprobl
em useasecondpar ameteras
sameasf irstparamet erformatt henonlyoracl
eserveraut omati
call
yconverts“dat
estri
ng”i
nto“datet
y pe”
.
Sol
ut i
on: SQL>sel ectto_date(‟27/ 06/05‟,
‟DD/MM/ YY‟)from dual;
27-
JUN- 05

SQL>sel ectto_date(‟09-feb-
15‟)+5from dual ;
14-feb-15
SQL>sel ectto_date(‟09-feb-
15‟,‟
DD-MM- YY‟)+5f r
om dual;
14-FEB- 15
Wr i
teaquer ytoconv ertgivendat estr
ingintocl i
entrequi
rementfor
matusi
ngt
o_char
()Gi
vendat
eis
->‟15-j
un-05
Expectedf ormat -
>„15/jun/05‟
SQL>sel ectt o_char(‟15-j
un-05‟ ,
‟dd/
mont h/yy‟)from dual;
Err
or :
invali
dnumber
SQL>sel ectt o_char(to_date(‟15-j
un-05‟)
,‟
dd/ mont h/yy‟
)from dual
;
15/jun/05Dat e:
24/3/15

Fil
lmode( FM):Wheneverwear eusi ngt o_char()iff or
mati seithermonth(or
)dayt henoracleserv
er
automatical
l
yretur
ns“spaces”whent hemont h( or)dayv al
uelessthanthemaximum lengt
hoft hemonth
(or
)day.Toov er
comethisproblem oracl
epr ovidedFi l
lMode(FM)whi chsuppr
essblankspacesandleadi
ng
zeros(
0).Thismodeisusedinsecondpar amet eroft heto_char(
).
Eg:SQL>selectt
o_char(
to_dat
e(‟15-JUN-05‟),
‟DD- MON- YY‟)fr
om dual;
MUARLISI R 2015
31

Cl
assi
fi
cat
ion:
Publ
ic
15-JUNE -05
SQL>selectt
o_char(to_ date(
‟15-JUN-05‟)
,„DD/FMMONTH/ YY‟)fr
om dual
;
15/JUNE/05
Writ
eaquer ytodi splaytheempl oyeeswhoarejoi
ningint
hemont hDecemberf
rom
“emp”tabl
eusingto_ char (
)?
Ans:SQL>select*from empwher eto_char(
HIREDATE,
‟MON‟ )
=„DEC‟;
OR
SQL>select*from empwher eto_char(
HIREDATE,‟
MM‟ )=‟
12‟;
OR
SQL>select*from empwher eto_char(
HIREDATE,‟
FMMONTH‟ )
=‟DECEMBER‟;

Wr i
teaquer yt odi splayt heempl oy eeswhoar ejoi
ningi nthey ear„81‟f r
om empt abl
eusi ngto_ char()
?
Ans: SQL>sel ect*f r
om empwher et o_char (hiredate,‟
yy‟
)=‟81‟ ;
SQL>sel ect
hir
edat e, to_char(hiredat e,
‟yyy y‟)from emp;
InOr acl e, whenev erwear epassi ngdat est r
ingi ntodatef uncti
onst henor acleserverautomat ical
lyconv ert
s
datest ringi nt odat ety pe.
Eg: SQL>sel ectlast _day (
‟12- JUN- 05‟ )f rom dual ;
30-JUN- 05
Buther epassedpar amet erf ormatmustbedef aultdatef ormatot herwiseor acl
eser v
erreturnsaner ror
.To
over comet hi sprobl em wemustuset o_ date().
Eg: SQL>sel ectlast _day (
„12- 06- 05‟ )f rom dual ;
Error: inv ali
dmont h
Solut i
on: SQL>sel ectl ast_day (to_ dat e(‟12- 06-05‟ ,
‟DD-MM- YY‟ )
from dual ;30-JUN-05
InOr acl ewhenev erwear ei nser tingdat esi ntodat edat at ypecol umnt henor acleserveraut omat ical
ly
conv er tsdat est ringi ntodat et y pewheni nser t
eddat est ri
ngi si nor acledat eformat.Ot herwiseor acle
serverr et urnsaner ror .Toov ercomet hispr obl em alsothenwemustuset o_date()
.
Eg:SQL>cr eat etabl et est(col1dat e);SQL>
i
nser ti ntot estv alues( sysdat e);SQL>sel ect*
fr
om t est ;
COL1
--
--
-----
---
24-MAR- 15
SQL>i nser tintotestv alues( ‟15- aug- 05‟ );SQL>
select*f rom t est;
COL1
--
--
-----
---
24-MAR- 15
15-AUG- 05
SQL>i nser tintotestv alues( ‟15- 08- 05‟ );
Error: notav alidmont h
SQL>i nser tintotestv alues( to_ dat e(‟15- 08-05‟ ,‟
DD- MM- YY‟));
MUARLISI R 2015
32

Cl
assi
fi
cat
ion:
Publ
ic
1rowi nserted
SQL>sel ect*from t
est
;
COL1
--
--
--
--
--
--
24-MAR- 15
15-AUG-05
15-AUG-05

Round()
,Trunc()usedindates:
I
nOr acl
e,“
date”datatypecontai
nsbothdat
eandt
ime.Whenev
erwear
eusi
ngt
her
ound(
)ort
runc(
)then
aut
omat i
cal
lydatepartchangedbasedonti
mepor
tion.

Dat
e:25/
3/15

Round()addsonedayt othegi v endat eiftimepor tioni sgreaterthanorequal to12noonandalsot i


me
port
ionaut omat i
cal
lysett o“zer o” .
Eg:SQL>sel ectto_char (sysdat e,‟DD- MON- YYYYHH24: MI:
SS‟ )fr
om dual ;
25-MAR- 2015 12: 24: 59
Whenappl yi
ngr ound( ):
SQL>sel ectt o_char(
round( sysdat e),
‟DD- MON- YYYYHH24: MI:SS‟)from dual;26-MAR-
201500: 00:00
Whenev erwear eusingt runc()or acleser verautomat icall
yr et
urnssamedat eiftimeport
ioni
sgreatert
han
orequal to12noonal soandal sot r
unc( )ti
mepor tioni ssett o“zero”(0)
Eg:SQL>sel ectto_char (tr
unc( sy sdat e),
‟DD- MON-YYYYHH24: MI:SS‟)fr
om dual ;
25-MAR-
201500: 00:00
Q)Wr i
teaquer yt odisplayt heempl oy eeswhoar ej oi
ningt odayfrom empt able?
Ans:SQL>sel ectinser tintoemp( empno, ename,hiredat e)
values(1,„MURALI ‟,
25-MAR-15)
;SQL>select*
fr
om emp;
SQL>sel ect*f rom empwher et runc( hir
edat e)=trunc( sysdate);

GROUPFUNCTI ON( OR)AGGREGATEFUNCTI ON:


Oracl
ehav i
ngfoll
owinggroupfunct
ion
max()
min()
avg()
sum()
count(
*)
count(
columnname)
I
nal l
databasesgroupfuncti
onsareoperateov
ernumberofv
alueswi
thi
nacol
umnandr
etur
nsasingl
e
val
ue
Max():I
tretur
nsmaxi mum val
uewithinacolumn.Eg:
SQL>selectmax(sal)f
rom emp;
6600
SQL>selectmax(hir
edate)fr
om emp;
MUARLISIR 2015
33

Cl
assi
fi
cat
ion:
Publ
ic
23-
MAY-87
SQL>sel
ectmax(
ename)f
rom emp;
WARD (
A=1………Z=26)

2.Min()
:
Eg:SQL>selectmin(sal
)fr
om emp;
750
Toknowt heseniormostempl oyee
SQL>selectmin(hir
edat
e)from emp;
17-DEC-
80
Inall
databasesystemswear enotall
owedtousegr
oupf
unct
ionsi
n“wher
e”cl
ause.SQL>
sel
ect*from empwher esal=min(sal
);
Err
or:gr
oupf unct
ionisnotall
owedin“wher
e”

Avg(
):Itretur
nsaver
agefrom numberdat
aty
pecol
umn.Eg:
SQL>
sel
ectavg(sal)fr
om emp;
2473.
21429
SQL>selectav g(
comm)from emp;

NOTE:Inal ldatabasesyst
emsbydef aul
tal
lgr
oupf
unct
ioni
gnor
esnul
lval
uesexcept
“count(
*)”.
Tocountal lnul
lv al
uesal
so:
SQL>sel ectavg(nvl
(comm,0)
)fr
om emp;
157.142857

Sum()
:Itretur
nst
otalf
rom numberdat
aty
pecol
umn.
Eg:SQL>selectsum(
sal)f
rom emp;
34625

Count(
*):I
tcountsnumberofrowsi
natabl
e(i
ncludi
ngnullv
alues)Eg:SQL>
sel
ectcount(*
)from emp;
Count(
columnname) :I
tcount
snumberofnotnullv
alueswi
thinacolumn.SQL>sel
ect
count
(comm)f rom emp;

SQL>sel
ectcount
(di
sti
nct
(deptno)
)fr
om emp;

GROUPBY:Thiscl
ausei
susedtodiv
idesimil
ardatai
temsi
ntosetofl
ogi
cal
groups.
Synt
ax:
sel
ectcol
umnname…..f
rom t
ablenamegroupbycol
umnname;

Dat
a:26/3/
15
Wri
teaquer
ynumberofemployeesi
neachdepar
tmentf
rom empt
abl
eusi
ng“
groupby
”?Ans:
SQL>
sel
ectdept
no,
count
(*)f
rom empgr
oupbydeptno;
DEPTNO COUNT(
*)
-
--
--
---
--
--
--
--
-
MUARLISI
R 2015
34

Cl
assi
fi
cat
ion:
Publ
ic
30 6
20 5
3
Wri
teaquerytodispl
aynumberofemploy
eesi
neachj
obf
rom empt
abl
eusi
nggr
oupby
?Ans:
SQL>
sel
ectj
ob,count
(*)f
rom empgroupbyjob;
JOBCOUNT( *
)
--
--
--
--
---
--
--
--
--
CLERK4
SALESMAN4
PRESIDENT1
MANAGER3
ANALYST 2
Wri
teaquerytodispl
aydept
no,mi
nimum andmaximum sal
aryf
rom empusi
nggr
oupby
?Ans:
SQL>
sel
ectdept
no,min(sal
),max(
sal
)fr
om empgroupbydept
no;
DEPTNO MI N(SAL)MAX(
SAL)
-
--
--
---
--
--
--
--
---
---
--
--
-
30 950 2850
20 800 3000
10 1300 5000

Note:I
nalldatabasesystemswecanal souse“ groupby”cl
auseswithoutusing“group”f
unct
ions.
Eg:SQL>selectdeptnofrom empgr oupbydept no;
RULE:Otherthangr oupf uncti
oncol umnsspeci fiedaft
ersel
ectthoseal lcolumnsmustbeusedi naf
ter
“gr
oupby”.Otherwiseoracleserverreturnsaner r
or“notaGROUPBYexpr ession”
.
Eg:SQL>selectdeptno,max( sal
),enamef rom empgr oupbydeptno,
ename;
ERRORatline1:
ORA-00979:notaGROUPBYexpr
essi
on

SQL>sel ectdept nofrom empgr oupbydept no, j


ob;
“Rev ersealsopossi ble”.
Not e:Whenev erwear esubmi tting“ groupby ”cl ausest hendatabaseserversselectthedatafrom thetable
from basedont hegr oupbycl ausecol umns.Thesecol umnsspacedat abaseser versgroupthedatai nthe
resultset,from t hisresultonl ywear esel ect
ingt hedat ausingnumberofcol umnsaf tersel
ectkeyword.
Not e:Whenev erwear eusi nggr oupf uncti
onswi thoutusi
ng“ groupby ”clauset hendatabaseser vers
execut est hesegr oupf unct ionsbasedonal lvaluesi nacol umn.Wher easwhenwear eusing“groupby ”
thent hesegr oupf unctionsexecut edeachandev erygroupwiseinat abl
e.
Not e:Gener all
yi nal ldatabasesy stemswear enotal lowedtodisplaygr
oupf unctionwithanothercolumns
toov ercomet hispr oblem wemustuse“ groupby ”clause.
Eg: step1:SQL>sel ectsum( sal)f r
om emp;
34627
Step2: SQL>sel ectdept no, sum( sal)fr
om emp;
Error:notasi ngl e-groupgr oupf unct i
on

MUARLISI
R 2015
35

Cl
assi
fi
cat
ion:
Publ
ic
Sol
uti
on:
SQL>sel
ectdept
no,
sum(
sal
)fr
om empgr
oupbydept
no;
DEPTNO SUM(
SAL)
-
--
--
---
--
--
--
--
-
9400
10875
8750
Eg:
SQL>sel
ectdept
no,
job,
sum(
sal
),count
(*)f
rom empgr
oupbydept
no,
job;
DEPTNOJOB SUM( SAL) COUNT(
*)
-
--
--
----
--
--
--
---
--
--
--
---
--
--
--
--
-
20CLERK 1900 2
30SALESMAN 5600 4
20MANAGER 2975 1
30CLERK 950 1
10PRESIDENT 5000 1
30MANAGER 2850 1
10CLERK 1300 1
10MANAGER 2450 1
20ANALYST 6000 2

Dat
e:27/
3/15

Wr i
teaquerytodispl
ayt hosedepartmentshav
ingmorethan3employ
eesfrom empt
abl
e?
Ans:SQL>selectdeptno,count(
*)from empgroupbydeptnowher
ecount(
*)>3;
Err
or:SQLcommondnotpr operl
yended.
Sol
ution:SQL>selectdeptno,coutn(*
)from empgroupbydept
nohavi
ngcount(*
)>3;

HAVI NGClause:Inalldatabsesy st
emsafter“groupby”clausewear enotall
owedt ouse“ where”clause.In
placeofthi
soneansi /isoSQLpr ovi
dedanotherclause“having”.General
lyifwewantt orestr
ictgroupsafter
“groupby”thenwemustuse“ hav i
ng”cl
ause.Generall
yin“ where”clausewear enotall
owedt ousegr oup
functi
onswher easinhav i
ngclausewecanal sousegr oupf uncti
ons.
Wri
teaquer ytodi
splaythosedepartmentshav i
ngmor et han10,000sun(sal)fr
om empt able?
And: SQL>selectdeptno,sum(sal)fr
om empgr oupbydept nohav i
ngsum( sal)
>10,000;

Dept
no sum(
sal
)
-
--
--
--
--
--
--
--
--
--
--
--
10 13550
12675

Wri
teaqueryt
odispl
ayyear,numberofemployeesperyeari
nwhichmorethanoneemployeewashi
red
fr
om emptabl
eusing“gr
oupby ”
?
And:SQL>sel
ectt
o_char
(hi
redate,
‟YYYY‟
),count
(*)f
rom empgroupby(t
o_char
(hi
redat
e,‟
YYYY‟)
);

MUARLISI
R 2015
36

Cl
assi
fi
cat
ion:
Publ
ic
OR
SQL>sel
ectto_char(
hir
edat
e,‟
YYYY‟
)year
,count
(*)f
rom empgr
oupby
to_
char
(hi
redate,
‟YYYY‟)
havi
ngcount(
*)>1;

year count
(*)
--
--
--
--
--
--
--
--
--
--
--
--
1981 10
1982 2

Invi
sibl
ecol umns:
Eg:SQL>sel ectdept no,sum(sal)f
rom emp
groupbydept no
havingsum( sal)>10000;
Herecount (*)isinvi
siblecol
umn.
SQL>sel ectdept no,sum(sal
)from emp
Groupbydept no
Havingcount (*)>3;
Deptno sum( sal
)
--
--
--
---
--
--
---
--
--
----
---
12675
8400
ORDERBY: Thi sclauseisusedtoar r
anget
hedat
ainsor
ti
ngor
deral
ongwi
th“
orderby
”cl
ausewear
eusi
ng
twokey words.

ORDERBY

asc(
ascendi
ng desc(
descendi
ng)

Bydef aul
t„orderby‟clausehav i
ng“Ascendingorder”
.
Syntax:SQL>sel ect*from tabl
enameor derbycolumnname[
asc/
desc]
;
Eg:SQL>sel ectsalfrom empor derbysal;
SQL>sel ectdeptno,salf r
om emp
orderbydept no,sal;
Eg:SQL>sel ectdeptno, count
(*)f
rom emp
Wher esal>1000
groupbydept no
havingcount(*)>3
orderbydepnt odesc;

Deptno count
(*)
--
--
--
--
--
--
--
--
--
--
--
30 4
MUARLI
SI
R 2015
37

Cl
assi
fi
cat
ion:
Publ
ic
20 5

Dat
e:28/
3/15

Note:
Inoraclewecanalsousecol
umnposi
ti
oninplaceofcolumnnamewit
hin“or
derby
”cl
ausewhi
chi
s
usedtoi
mpr oveper
for
mancequery.Eg:
SQL>sel
ect*from emporderby6desc;

ROLLUP, Cube:
Oracl e8i i
ntroducedr ollup, cubecl auses.Thesecl ausesar eusedalongwi thgroupbyclauseonl
y.These
cl
ausesar eusedt ocalculatesubt ot al
,gr
andtot alautomat i
call
y.
Syntax: selectcol 1,col2,……. .from t abl
ename
gr oupbyr ol
lup(col1,col2,..
);
Syntax: selectcol 1,col2,….Fr om t ablenamegr oupbycube( col
1,col
2,…);
Rollupi susedt ocal culatesubt otal val
uebasedonasi nglecolumnwher easi fwewantt ocal
cul
ate
subt otalvaluebasedonnumberofcol umnwi set henwemustusecube.Eg: SQL>selectdept
no,j
ob,
sum( sal
)from empgr oupbyr ollup(deptno,j
ob) ;
SQL>sel ectdept no, j
ob, sum( sal)
, count(
*)fr
om empgr oupbycube( deptno,j
ob);
Eg:SQL>sel ectename, sum( sal)from empgr oupbyr oll
up(ename);

JOINS:Joinsar eusedtoret
riev
eddatafr
om mul
ti
pletabl
es.Inalldatabaseswhenwear
ejoi
ngi
n“n”t
abl
es
thenwemustuse“ n-1”j
oini
ngcondi
ti
ons.Or
acl
ehavingfol
lowingtypesofj oi
ns.
Equijoing(or)I
nnerj
oin
Nonequi j
oin
Sel
fjoin
Outerjoin

These4j oinsarealsocal
l
edas“
8ij
oins”
.
9ij
oinsoransij oins.
I
nnerj oin
Leftouterjoin
Rightout erj
oin
Fullouterjoi
n
Natural j
oin

Inoracl
e,wecanal soretr
ievedatafr
om mul t
ipl
etabl
eswit
houtusi
ngj
oincondi
ti
onint hi
scaseoracl
e
serv
erinternall
yusescrossjoi
n.Butcrossj
oinisimpl
ement
edbasedonCart
esi
anproductthat
‟swhythi
s
i
nternalj
oinreturnsmor
edupl i
cat
edata.
Eg:SQL>sel ectename,
sal,dname,l
ocf r
om emp,dept
;

Equij
oin(or)Innerj oin:Basedonequal
it
ycondi
ti
onwear eretr
iev
ingdatafrom mul
ti
plet
ables.Her
e
j
oini
ngconditi
onal columnsmustbelongstosamedatat
ype.
General
l
y,whent ableshav i
ngcommoncolumnsthenonlyweareusingt
his“j
oin”
.
MUARLISIR 2015
38

Cl
assi
fi
cat
ion:
Publ
ic
Synt
ax:sel
ectcol
1,col2,
….
fr
om tabl
ename1,t
ablename2
wheretabl
ename1.
commoncolumnname=t
abl
ename2.Commoncol
umnname;

tablename.Commoncol umnnamei saj oi


ncondition
Eg: SQL>sel
ectename, sal,
deptno,dname, l
ocfrom emp,deptwher
eemp. dept
no=dept.dept
no;
Error:col
umnambi guouslydefi
ned.
Solution:
SQL>selectename, sal
,dept.
deptno,dname,locfr
om emp,deptwhereemp.deptno=dept
.dept
no;

Dat
e:30/
3/15

NOTE:Gener all
y,toavoi
dambi guit
yinf uturewemustspeci f
yev ery“col
umnname”alongwithtabl
ename
usi
ng„.‟(Fullst
opordot)operator.
NOTE:Inal l
databaseswecanal socreat eali
asnamesf ort
het ablein“f
rom”cl
auseofthe“
joi
nconditi
ons”
.
Thesealiasnamesar eal
socalledas“ Referencenames”.Theser efer
encenamesareusedi
nselectl
ist
,
usedinjoini
ngconditi
on.Synt
ax:f r
om tablenameal i
asname1,tablenameali
asname2.
Thesealiasnamesmustbedi fferentnames.
USINGALI ASNAMES:
SQL>selectename, sal
,d.
deptno,dname, locfrom empe,deptdWher e
e.
deptno=d. deptno;

ENAME SAL DEPTNODNAME LOC


--
--
--
--
---
--
--
--
--
---
--
---
--
---
--
--
--
--
--
----
--
--
--
--
CLARK 2450 10ACCOUNTING NEW YORK
KING 5000 10ACCOUNTI NG NEW YORK
MILLER 1300 10ACCOUNTING NEW YORK
JONES 2975 20RESEARCH DALLAS
FORD 3000 20RESEARCH DALLAS
ADAMS 1100 20RESEARCH DALLAS
SMITH 800 20RESEARCH DALLAS
SCOTT 3000 20RESEARCH DALLAS
WARD 1250 30SALES CHI CAGO
TURNER 1500 30SALES CHI CAGO
ALLEN 1600 30SALES CHICAGO
JAMES 950 30SALES CHI CAGO
BLAKE 2850 30SALES CHI CAGO
MARTI N 1250 30SALES CHI CAGO
Intheabovequer y,heredeptno(“
40”)doesn‟ tdi
spl
ayedifwear eusingdept.
deptnoalso.
NOTE: I
nal ldat
abasesalway sequij
oinsr et
urnsmatchi
ngr owsonly.
Writ
eaquer ytodispl
aytheemploy eeswhoar eworki
ngi nthelocati
onChicagofr
om emp,deptt
abl
es
usi
ngequi join?
Ans:SQL>sel ectl
oc,enamef rom emp, deptwhereemp.deptno=dept.dept
nogroupbylochav
ing
l
oc=‟chicago‟;
err
or:notaGROUPBYexpr ession
MUARLISI
R 2015
39

Cl
assi
fi
cat
ion:
Publ
ic
Sol
ution:
SQL>selectename,l
ocfr
om emp,deptwher
e
emp.deptno=dept
.dept
noandl
oc=‟chi
cago‟
;
ENAME LOC
--
--
--
--
---
--
--
--
--
WARD CHI CAGO
TURNER CHICAGO
ALLEN CHI CAGO
JAMES CHICAGO
BLAKE CHICAGO
MARTI N CHICAGO
Note:I
fwewantt ofil
terthedataafterj
oiningcondit
ionthenwemustuse“ and”oper
atori
n8ij
oinswher
eas
i
n9i j
oinsweareusingei ther“
and”operatoror“where”clausealso.
Q)Wr i
teaquerytodisplaydname, sum(sal)fr
om emp, depttablesusingequijoi
n?
Ans:SQL>selectdname, sum(sal
)from empe, deptdwher ee.deptno=d.
deptnogroupbydname;
DNAME SUM( SAL)
-
--
--
--
--
--
--
---
--
--
--
--
ACCOUNTING 8750
RESEARCH 10875
SALES 9400

SQL>selectdept.
dept
no,
dname,
sum(
sal
)fr
om emp,
deptwher
eemp.
dept
no=dept
.dept
nogr
oupby
dept
.deptno,dname;
DEPTNODNAME SUM(
SAL)
-
--
--
---
--
--
--
--
--
--
---
--
--
--
--
10 ACCOUNTI NG 8750
20 RESEARCH 10875
30 SALES 9400
Wr i
teaquerytodispl
aynumberofemployees,min(sal
),max(sal
),sum(sal
)ineachlocat
ionfrom emp,
depttablesusi
ngequi j
oin?
Ans:selectl
oc,count
(*),
mi n(
sal
),max(
sal
),
sum(sal)fr
om emp, deptwhereemp.deptno=dept.
deptnogroup
byloc;
LOC COUNT( *) MIN( SAL) MAX( SAL)SUM( SAL)
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
---
--
--
--
---
--
----
---
NEW YORK 3 1300 5000 8750
CHICAGO 6 950 2850 9400
DALLAS 5 800 3000 10875

SQL>sel
ectdname,
sum(
sal
)fr
om empe,
deptdwher
ee.
dept
no=d.
dept
nogr
oupbydnamehav
ingdname;
DNAME SUM(SAL)
-
--
--
--
--
--
--
---
--
--
--
--
RESEARCH 10875
SQL>sel
ectdname,
sum(
sal
)fr
om empe,
deptdwher
ee.
dept
no=d.
dept
nogr
oupbyr
oll
up(
dname)
;
DNAME SUM(SAL)
-
--
--
--
--
--
--
---
--
--
--
--
ACCOUNTING 8750
RESEARCH 10875
SALES 9400
29025

MUARLISI
R 2015
40

Cl
assi
fi
cat
ion:
Publ
ic
NonEquiJoin:Basedonotherthanequal
i
tycondi
ti
on(notequalt
o,>,
<,
>=,
<=,
bet
ween,i
n,
….)wecan
r
etr
iev
edatafrom mul
ti
plet
abl
es.Inor
acl
e,t
hisj
oini
salsocal
ledas

Between….
.andJoin”
.

Dat
e:31/
3/15

Eg:SQL>cr eat
etabl
etest1(
deptnonumber
(10)
,enamev
archar
2(20)
);
SQL>insertint
otest
1values(10,
‟a‟
);
SQL>insertint
otest
1values(20,
‟b‟
);
SQL>select*from t
est
1;
DEPTNO ENAME
-
--
--
---
--
--
--
--
--
---
a
b

DEPTNO DNAME
--
---
---
---
--
----
---
--
10 c
d
e
SQL>sel ect*f r
om t est1,
t est2wher et est1.dept no>test2.deptno;DEPTNO
ENAMEDEPTNODNAME
--
---
---
---
--
----
---
--
---
---
---
---
---
--
----
--
20 b 10 c
NOTE: Inor acle,wecanal sousenon- equi joinwhent ablesdoesnothav ecommoncol umns.
Eg: select*f rom sal grade
SQL>sel ectename, sal,l
osal ,
hisalfr
om emp, salgradewher esal betweenlosalandhisal;
OR
Wher esal>=losal andsal <=hi sal;
3.SELFJOI N:Joi ni
ngat abl etoitselfiscal led“ selfjoin”
.Her ejoiningcondit
ionalcol
umnsmustbel ongsto
samedat atype.Bef orewear eusingsel fjoinwemustcr eateali
asnamesf orthetablein“f
rom”clause.
Synt ax:from t ablenameal i
asname1, tablenameal i
asname2;
Gener all
y,i fwewantt ocompar etwodi fferentcol umnv al
uesi nasi ngl
etablethenwemustusesel f
-j
oin.
Buther et heset wocol umnsmustbel ongt osamedat atype.
Wr i
teaquer yt odisplayempl oyeenamesandt hei rmanagernamesf r
om empt ableusi
ngselfjoi
n?
Ans: SQL>sel ecte1. ename“ employees” ,e2. ename“ manager s”from empe1, empe2
Wher ee1. mgr =e2.empno;

MUARLISI
R 2015
41

Cl
assi
fi
cat
ion:
Publ
ic
SQL>selecte1.ename“ employees”
,e1.mgr
,e2.
empno,e2.
ename“managers”fr
om empe1,empe2
Wheree1.mgr=e2. empno;
Writ
eaquer yt odisplaytheemployeeswhoareget
ti
ngmoresal
arythanthei
rmanagersal
aryf
rom emp
tabl
eusing“selfjoin”
?
Ans:SQL>selecte1. name“ employees”,
e1.
sal
,e2.
sal
,e2.
ename“manager”fr
om emp
e1,empe2
wheree1.mgr=e2. empno
ande1.sal
>e2.sal;
employees sal salmanager
--
--
--
--
--
--
--
--
--
--
--
---
---
---
--
--
--
---
--
---
-
SCOTT 3600 3375 JONES
FORD 3600 3375 JONES

Wri
teaquer ytodi
splaytheemploy
eeswhoarejoini
ngbeforethei
rmanager
sfrom emptabl
eusi
ngsel
f
j
oin?
Ans:SQL>selecte1.
name“ employ
ees”,
e1.
hir
edat
e,e2.hi
redat
e,e2.
ename“manager”f
rom emp
e1,
empe2
wheree1.mgr=e2.
empno
ande1.hi
redat
e<e2.Hiredate;

Dat
e:1/4/
15
WhentouseAl
iasnames:

I
nal ldatabasessyst
emswhenev erwear eref
ersametabl
emor ethanonetimef oewueryresul
tsthen
wemustcr eate“t
abl
ealias”names.Thesealiasnamesarealsocal
ledas ”Referencenames”.These
al
iasnamesi nter
nal
lybehavesli
keat ableswhenqueryexecuti
ontime.Theseal i
asnamesmustbe
di
fferentnames.

Sy
ntax:f
rom t
abl
enameal
i
asname1,
tabl
enameal
i
asname2;

Wr
it
eaqueryt
odi
splayt
heempl
oyeeswhoar
eget
ti
ngsamesal
aryasscot
tsal
aryf
rom empt
abl
e
usi
ngt
ableal
i
asnames?

Ans:
SQL>sel
ecte2.
ename,
e1.
sal
from empe1,
empe2wher
ee1.
sal
=e2.
sal
ande1.
ename=‟
SCOTT‟
;

OUTERJOIN:Thi
sj oi
nisusedtoretr
iev
eal lr
owsf r
om onetabl
eandmatchi
ngr
owsf
rom anot
her
t
abl
e.Gener
all
y,usi
ng“ equij
oin”wearer et
ri
evingmat chi
ngr
owsonly.I
fwewanttoret
ri
evenon-
mat
chi
ngrowsalsothenweareusingjoi
noperator(
+).

Wi
thi
njoi
ningcondi
ti
onof“
equi
joi
n”t
hisj
oini
scal
l
ed“
ORACLE8i
Out
erj
oin”
.

NOTE:Joi
noper
atorcanbeusedonl
yonesi
deatat
imeonej
oini
ngcondi
ti
on.

MUARLISI
R 2015
42

Cl
assi
fi
cat
ion:
Publ
ic
Eg:
SQL>sel
ectename,
sal
,d.
dept
no,
dname,
l
ocf
rom empe,
deptdwher
ee.
dept
no(
+)=d.
dept
no;

e.
dept
no-
 mat
chi
ngr
ows

d.
dept
no-
 al
lrows

9i
JOI
NSorANSIJOI
NS:

I
nnerj oin
Leftout erjoi
n
Rightout erjoi
n
Fullout erj
oin
Natur aljoi
n
Innerj oin:Thisjoi
nalsoret
urnsmat chi
ngr owsonl y
.Whenev ertabl
eshav
ingcommoncol umns
thenonlywear eusi
ngthi
sjoi
n.Herealsojoi
ningcondit
ionalcol
umnsmustbelongstosomedatatype.
I
nnerj oi
n( 9i)perfor
manceisver
yhighcompar etooracl
e8i equijoi
n.
Eg:SQL>sel ectename,sal
,d.
deptno,
dname, l
ocf r
om empej oi
ndeptdone.deptno=d.
dept
no;

Wri
teaquerytodispl
aytheempl
oyeeswhoarewor
kinginthelocat
ion„
CHICAGO‟from emp,
dept
tabl
esusi
ng9iinnerj
oin.
Ans:SQL>sel
ectename,locfr
om empejoi
ndeptdone.deptno=d.
deptnowher
eloc=‟
CHICAGO‟;

Eg:SQL>cr eatetablet1( avarchar2(


10)
,bvarchar2(
10),
cvar
char
2(10)
);SQL>i
nser
t
i
ntot1v alues( „
x‟,‟
y‟,
‟z‟);
SQL>i nsertintot1values(„p‟,
‟q‟,
‟r
‟);
SQL>sel ect *f r
om t 1;
SQL>cr eatet ablet2(av archar2(
10),bv
archar2(
10));
SQL>inserti nt
ot 2values( „
x‟,
‟y‟)
;
SQL.>select*f r
om t2;

A B C A B
-
---
--
--
--
--
--
--
---
--
--
--
- -
--
--
--
--
--
--
--
---
--
-
X Y Z X Y
P q r
8iequij
oin:
SQL>select*from t
1,t
2wheret
1.a=t2.aandt1.
b=t2.b;
9ii
nnerjoin:
SQL>select*from t
1joint
2ont1.a=t2.
awheret1.b=t2.
b;
Out
put
:
A B C A B

MUARLISI
R 2015
43

Cl
assi
fi
cat
ion:
Publ
ic
-
--
--
--
--
--
--
--
--
--
--
--
--
- -
--
--
--
--
--
--
--
--
--
--
X Y Z X Y

Dat
e:2/
4/15

Usingclause:
In9ij
oinswecanal souse“USI
NG”clausesi
nplaceof“ON”clause.“Usi
ng”cl
auseperf
ormancei
sver
y
highcompar eto“ON”clauseandal
sowhenwear eusi
ng“USING”clausethenoracl
eserv
er
automaticall
yret
urningcommoncolumnsont i
meonl y
.Synt
ax: sel
ect*fr
om tabl
ename1joi
n
tabl
ename2usi ng(commoncol umnnames);
Eg:SQL>sel ect*fr
om t1joi
nt2
usi
ng( a,
b);
Output:

A B C
--
--
----
--
---
--
--
X y z
Not e:whenev erweareusing“Using”cl
auset
henwear
enotal
l
owedt
ouseal
i
asnameorj
oini
ngcondi
ti
onal
columns.
Eg: Selectename,sal
,
deptno,dname,l
oc
fr
om empej oi
ndeptd
using( deptno);

LeftOut erJoin:
Thisjoi
nal waysr eutur
nsallr
owsfrom l
eftsi
det
abl
eandmat chi
ngrowsfr
om reightsi
detabl
eandal
so
ret
urns“NULL”v aluesinpl
aceofnon-
mat chi
ngr
owsinanot
hertabl
e.Eg:
select*from t
1;
A B C
-
---
--
--
---
--
---
-
X y z
P q r
SQL>sel ect*from t 2;

B
-
--
--
--
--
y
St
SQL>select*f
rom t
1lef
touterjoi
nt2ont 1.
a=t
2.aandt
1.b=t
2.b;
A B C A B
-
--
--
--
--
--
--
---
--
- --
---
--
--
--
--
--
--
--
--
X Y Z X Y
P q r (null
) ( null
)

MUARLISI
R 2015
44

Cl
assi
fi
cat
ion:
Publ
ic
Ri
ghtOuterJoin:
Thi
sJoinret
urnsallr
owsf r
om ri
ghtsi
detabl
eandmatchi
ngrowsf
rom l
eftsi
det
abl
eandal
sor
etur
ns
nul
lval
uesinplaceof“non-
matchi
ng”rowsinanot
hert
abl
e.

FullOut erJoin:
Thisjoinreturnsalldatafr
om allthet abl
esi
tisthecombinati
onoflef
tandrightouterj
oins.Thi
sjoin
al
way sretur nsmat chi
ngandnon-mat chingr
ows.Andalsothisjoi
nret
urnsnullv
aluesinplaceofnon-
matchingr ows.
Eg:SQL>sel ect*fr
om t1ful
louterjoint2ont1.
a=t2.
aandt1.b=t
2.b;
A B C A B
--
--
--
--
---
--
--
--- --
--
--
--
--
---
X y z x y
P q r nul
l null
Null nul l nul l s t

Nat uralJoin:Thisjoinalsor etur


nsmat chi
ngr owsonl y.Whenwear eusing
“NaturalJoin”thenwear enotallowedt ousedt ousej oi
ningcondi
ti
on.I
nthi
scaseor
acleserv
eronl
y
i
nternallyusesj oi
ningconditi
on.Buther eresour
cet ablesmustcontai
ncommoncolumnname.
Syntax:select*f r
om tablename1nat uraljoi
ntablename2.
Note:Nat uralJoinperformanceisv er
yhi ghcompar edt oi
nnerjoi
n.
Note:Thi sjoinint
ernal
lyuses“ USING”clause.That‟swhyt hisjoi
nal
soret
urnscommoncolumnsone
ti
meonl y.
Eg:SQL>sel ect*from t1naturalj
oint2;Output:

A B C
--
--
--
--
--
---
--
--
X y z
Note:Whenwear eusi
ng“Natural
”joinal
sothenwearenotall
owedtouseali
asnameonjoi
ning
condit
ionalcol
umnbecausenatur
al j
oini
nter
nall
yuses“USI
NG”cl
ause.Eg:
SQL>select
ename,sal,
dept
no,
dname,l
ocfrom empenat ural
joi
ndeptd;

CROSSJOI N:
Eg:sel ectename, sal
,dname, l
ocf rom empcr ossj oindept;
Joiningmor ethan2-tables.(
exampl e3t ables):
8iJOI NS
Synt ax:SQL>sel ectcol1,
col2,…..fr
om t able1,table2,tabl
e3
Wher et abl
e1.commoncol name=t able2.
commcol nameand
tabl
e2.Commcol name=table3.
commcol name;
9iJOI N:
Synt ax:SQL>sel ectcol1,
col2,…f r
om tabl e1joint able2on
table1.commcol name=t able2.commcol namej oint able3
MUARLISI
R 2015
45

Cl
assi
fi
cat
ion:
Publ
ic
ont
abl
e2.
commcol
name=t
abl
e3.
commcol
name;

CONSTRAI NTS:
Constr
aintsar
eusedt
opr eventsorst
opsinval
iddat
aentr
yint
oourtabl
es.Gener
all
yconst
rai
ntsar
e
creat
edont abl
ecol
umns.Oracleser
verhav
ingfol
lowi
ngt
ypesofconst
rai
nts.
Notnull
Unique
Pri
mar ykey
Forei
gnkey
Check

Thesear
ecal
l
ed“
Const
rai
nts(
or)Const
rai
ntt
ypes”
.

Dat
e:3/
4/15

Al
ltheabov
econst
rai
ntsar
ecr
eat
edi
ntwoway
s:

Usi
ngcolumnlevel
Usi
ngtablel
evel
Usi
ngCol umnlevel
:Int hismethoswearedefi
ningconstr
aint
soni ndivi
dualcolumns.Thati
s
wheneverwearedefi
ningthecol
umnthenonl
yimmediat
elywearespecif
yingconstr
aintt
ype.

Synt
ax:
creat
etabl
etabl
ename(
col
1dat
aty
pe(
size)const
rai
ntt
ype,
col
2dat
aty
pe(
size)const
rai
nt
ty
pe,
…..
);

Usi
ngTablelevel
:Int
hismet
hodwearedefi
ningconst
rai
ntsongr oupofcol
umnsi.e.,i
nthi
s
methodf
ir
stwearedef
ini
ngal
lcol
umnsandl
astonl
ywear especi
fyi
ngconst
rai
ntt
ypealongwit
h
gr
oupofcolumns.

Syntax: cr eat
e t able tabl
ename(
col
1 dat
aty
pe(
size)
,col
2 dat
aty
pe(
size)
,…. ,
constrai
ntt
ype(col
1,col
2,….
))
;

NotNULL:Thisconstr
aintdoesn‟
tsuppor
ttabl
elev
el.Thi
sconst
rai
ntdoesn‟
taccept
snul
lval
ues.
Buti
twil
lacceptsdupl
icateval
ues.

Columnl evel:SQL>cr eatet ablet1(snonumber (


10)notnul l
, namev archar 2(10))
;
Testi
ng: SQL>i nserti
ntot 1v alues(nul
l,
‟abc‟
);
ORA-1400: cannotinser tnullintoSNO;
Tablelevel:SQL>cr eatetabl et1(snonumber (
10),namev ar
char 2(
10), notnul l
(sno,
name));
UNI QUE:Thi sconstraintisdef i
nedoncol umnl ev
el,tablelevel
.Thi sconst rai
ntdoesn‟taccept
s
duplicat
ev alues.Buti twillacceptsnullv
alues.
Note:Whenev erwear ecr eatinguniqueconstrai
ntsthenor acleserveri nt
er nal
lyautomati
call
ycreat
esb
-
treeindexont hosecolumns.
Columnl evel:SQL>cr eatet ablet2(snonumber (
10)unique, namev archar 2(10));
MUARLISI R 2015
46

Cl
assi
fi
cat
ion:
Publ
ic
Table l evel
: SQL> cr
eate t able t2(
sno number
(10)
, name v
archar
2(10)
,
unique(sno,
name) );
Tablecreated
Eg:SQL>i nsertint
ot 3(….
)
SNO NAME
--
--
---
--
--
---
--
--
--
--
-
1 murali
1 abc
SQL>sel ect*from t3;
Err
or:ORA- 00001:Uni queconstr
aintv
iol
ated.

3.Pri
mar yKey :Pri
mar ykey“ Uni
quelyidenti
fyi
ngar ecordinat able”.Therecanbeonl yoneprimarykey
i
nat ableandal soprimarykeydoesn‟ tacceptsdupl i
cat
enul lvalues.Note:Whenev erwearecreati
ng
pri
mar ykeyt henor acl
eserv erautomatical
lycreatean“b-tree”indexesont hosecol umns.
Columnl evel:SQL>cr eatetablet4(snonumber (10)pri
mar ykey, namev archar
2(10));Tabl
ecreat
ed
Tablelevel
: SQL>cr eatetablet4(snonumber (10),namev archar2(10),pr
imarykey(sno,name))
;
Thi
si salsocal ledas“Composi t
ePr i
mar yKey”i.
e.,i
tist
hecombi nati
onofcolumnsasa“ si
ngle
pri
mar ykey”.

Forei
gnKey :I
fwewantt oestabli
shesrelat
ionshi
pbetweentablesthenwear eusi
ng
“Refer
enti
alInt
egri
tyConstr
aints”(Forei
gnKey ).Onetabl
eforei
gnkeymustbel ongstoanothertable
“pri
marykey”.Herethesetwocol umnsmustbel ongtosamedat atypes.Alwaysforei
gnkeyv alues
basedon“ pr
imarykey”val
uesonly.Generall
y,pri
marykeydoesn‟tacceptsdupli
cate,
null
,val
ueswher e
asforei
gnkeyacceptsdupli
cate,nullv
alues.

Dat
e:4/
4/15

Columnl evel(“Refer
ences”):
Syntax:
cr eat
et abl
etablename(col1datatype(
size)ref
erencesmast
ert
abl
ename(
pri
mar
y
col
umnname) ,….)
;
Eg:SQL>cr eatetableh4(snonumber (10)ref
erencest4);Or
SQL>creat etableg4(xnumber (
(10)refer
encest 4(
sno));

TableLev el
:(Forei
gnkeyrefer
ences)
Syntax: cr eate t abl
e t ablename(col1 dat atype(si
ze),
col2 dataty
pe(si
ze),…., forei
gn
key(
col1,col
2));
Eg:SQL>cr eatetabl
eh5(snonumber (10)
,namev ar
char2(10),
forei
gnkey(sno,
name)r eferencest5);
Whenev erwear eestabl
i
shingrelat
ionshi
pbetweentablesthenoraclev
iol
atesfol
lowingt wor ul
es:-
MUARLISI R 2015
47

Cl
assi
fi
cat
ion:
Publ
ic
Del
eti
onin“MASTER”tabl
e
I
nsert
ioni
n“CHILD”t
able

Deletionin“ Mast er”table:Whenwet rytodel et


emast ertablerecordifchil
dt ablerecor
dsar eexist
,
thenor acl
eser verr eturnsaner ror“ORA-2292”t oov er
comet hi
sproblem fi
rstwear edelet
ingchild
tabl
er ecordsin“ childt able”andt henonlywear edeleti
ngappr opri
ate“mastert able”r
ecordswi t
hin
mast ertable.Other wiseusi ng
“ondel et
ecascade”cl ause.
ON DELETECASCADE:Whenwear eusi ngt hisclauseinchi ldtabletheni fwear edel et
inga
“mast ertable”recor dwi t
hinmast ertabl
et henor acleserverautomat i
call
ydel etes“mastertable”
recordsinmast ertableandal sodelet
escor respondingrecordsin“chil
dtable”.
Syntax:cr eatet ablet ablename( col
1dat atype(si
ze)r ef
erencesmast er
tablename
(pri
mar ykeycol name)ondel etecascade,…..
);
Eg:SQL>cr eatetabl emas( snonumber (
10)pr i
mar ykey);
SQL>
i
nserti nt
omasv alues( ……..);
SQL>sel ect*f rom mas;
SNO
-
---
1
2
3

SQL>createtablechil
d(snonumber
(10)r
efer
encesmas(
sno)ondel
etecascade)
;SQL>i
nser
t
i
ntochi
ldv al
ues(……..
);
SQL>select*from chil
d;
SNO
-
--
--
1
1
2
2
3
3

Test
ing:(del
eti
oninmastert
abl
e)
SQL>deletef
rom maswheresno=1;
1rowdeleted
SQL>sel
ect*f r
om mas:
SQL>sel
ect*f r
om chi
l
d;
SNO SNO
-
--
- --
--
2
2
MUARLISIR 2015
48

Cl
assi
fi
cat
ion:
Publ
ic
3
3
Oracl
eal sosuppor t
sanotherclausealongwithf or
eignkey“ONDELETESETNULL” .
ONDELETESETNULL:
Whenev erwear eusingthi
sclauset he“chi
ldtable”thenifwedelet
ingamastert
ablerecor
dthen
oracl
eser verautomati
call
ydeletesprimarykeyv al
uei nmastert
ableandal
socorrespondi
ngfor
eign
keyvaluesar eautomati
call
ysett onulli
nchil
dt able.Synt
ax:

createt
abl
etablename(col
datat
ype(si
ze)
refer
encemastertabl
ename(pr
imarykeycol
name)ondel
etesetnul
l
,……)
;

INSERTI ONI NCHI LDTABLE:I nOr acle,whenwear etryi


ngt oinser
tot
herthanpr
imarykeyval
ues
intoFor eignkeyt henor acleser verreturnsaner ror“ORA- 2291”.
Becausei nal l
dat abasesy stemsal way sforei
gnkeyv al
uesar ebasedonpri
marykeyval
uesonly
.
Eg:SQL>i nser tintochi ldv alues( 5);
ORA- 2291: Intergrit
yconst r
ai ntv i
olated-parentkeynotf ound.
Soluti
on: SQL>i nser tintomasv alues(5);
SQL>sel ect*f rom mas;
SQL>i nser tintochi ldv alues( 5);
SQL>sel ect*f rom mas;
Exampl ebasedondept (mast ertable),emp( childtable):
1)Del et
ioni nMast ert able:
SQL>del et ef r
om deptwher edept no=10; ORA- 2292:integri
ty
constrai
ntv i
olated-chi ldrecor df oun.
2)Inserti
oni nchi ldt able:
SQL>i nser tintoemp( empno, dept no)values(5,90);
ORA- 2291:Int
egrit
y
constrai
ntv i
olated–par entkeynotf ound

Dat
e:6/
4/15

I
nor acle,wear enotal lowedt odefinelogicalcondti
onsusing“ SYSDATE”wi
thi
ncheckconst
rai
nt.
COLUMNLEVEL:
Syntax: cr eate t able t ablename( col1 dataty
pe(
size) check( l
ogical condit
ion)
,col
2
datatype(si
ze) ,
…..)
;
Eg:createtabl et6(salnumber (10)check( sal
>5000) )
;
SQL>i nsertintot6v alues(3000);
Err
or:checkconst raint(
scott.
syst_c005513)v i
olat
ed
SQL>i nsertintot6v alues(9000);
SQL>sel ect*f rom t6;
SAL
--
--
-
9000
MUARLISI R 2015
49

Cl
assi
fi
cat
ion:
Publ
ic
Eg: creat etabl et 7(namev ar char2( 20)check( name=upper (name) ))
;SQL>
i
nser ti ntot7v alues( „
mur ali
‟ );
Error: checkconst raint(scot t.syst_c00514)v i
ol atedSQL>
i
nser ti ntot7v alues( „MURALI ‟);
SQL>sel ect*f rom t 7;
NAME
--
---
-
MURALI
Tabl el evel:
Eg: SQL>cr eatet ablet 8(namev archar 2(20) ,sal number (
10) ,
check( name=upper (
name)andsal >5000) );
Assi gnUserdef inednamest oConst raints( OR)Userdef inedConst rai
ntNames:
In alldat abase sy stems whenev erwe ar e cr eat ing const raintst hen database ser versinternall
y
automat i
callygener atesanuni quei dent if
icationnumberf orindentifyi
ngaconst raintuniquely.
InOr acleal sowhenev erwear ecr eat ingconst raint sthenor acleser veraut omat icall
ygener atesan
uniquei dent if
icationnumberi nthef ormatof“ SYS_ Cn” .Thi siscalled“ Predefi
nedConst raintName” .In
placeoft hisonewecanal socr eat eourownnameusi ng“ Const rai
ntKey word”.Thi siscall
ed“ Used
definedConst r
aintName” .
Synt ax: Const raintuserdef inednameconst raint_ t
y pe; Here,
const raint->key wor d
Const raint_type->Notnul l,uni que, primar ykey , f
or eignkey , checkUser
definedname- >const raintnameEg1: (Pr edef inedConst raintName)
SQL>cr eatet ablet 10( snonumber (10)pr imar ykey ;
Test ing:
SQL>i nser tintot 10v alues( 1);
SQL>i nser tintot 10v alues( 1);
Error: uniqueconst raint(SCOTT. SYS_ C005516)v iolat ed
Eg2: Userdef i
nedConst raintName
SQL>cr eatet ablet 11( snonumber (10)const raintp_ abcpr imar ykey);
Test ing:
SQL>i nser tintot 11v alues( 1);
SQL>i nser tintot 11v alues( 1);
Error: uniqueconst raints( SCOTT. P_ ABC)v iolated
DataDi ct i
onar i
es:
Whenev erwear ei nst all
ingor acleser vert henor acl eser veraut omat i
callycreatessomer eadonl y
tables.Theser eadonl ytabl esar eal socal ledas“ Dat aDict i
onar i
es”.

MUARLISI
R 2015
50

Cl
assi
fi
cat
ion:
Publ
ic
Note1:InOracl
e,al
lconst
rai
ntsinf
ormati
onst or
edunder“ user
_constr
aint
”datadi
cti
onar
y.
Eg:SQL>descuser_const
rai
nts;
SQL>selectCONSTRAINT_NAME, CONSTRAI NT_TYPEf r
om USER_ CONSTRAINTSwhere
tabl
e_name=‟EMP‟;
Output:
CONSTRAI NT_NAME CONSTRAI NT_TYPE
--
--
--
--
--
--
--
--
--
--
--
--
-- -
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
---
--
-
PK_EMP P
FK_DEPTNO R

Tabl
e_name=‟
EMP‟

Here, EMPiscapi talletter


NOTE2: InOracle,ify ouwantt ov i
ewcolumnnamesal ongwithconst
rai
ntnamesthenweareusi
ng
“user_cons_columns” .
Eg:SQL>descuser _cons_ columns;
SQL>sel ectconst r
aint _
name, column_namef rom user_cons_col
umnswhere
table_name=‟EMP‟ ;
Output :
CONSTRAI NT_NAME COLUMN_ NAME
--
--
----
--
--
--
--
--
--
---
- --
--
--
---
--
--
--
--
--
FK_DEPTNO DEPTNO
PK_ EMPNO EMPNO
NOTE3: InOracle,ify ouwantt ov i
ewlogicalcondit
ionsofthecheckconstr
aintt
henweareusi
ng
“search_condit
ion”f rom “user _
constr
aints”datadi
ctionary.
Eg:SQL>descuser _constraints;
SQL>sel ectsearch_ conditionfrom user_const
rai
ntswher e
table_name=‟T7‟ ;
SEARCH_ CONSTRAI NTS
--
--
----
--
--
--
--
--
--
---
---
-
name=upper (name)

Dat
e:7/
4/15

I
nOr
acl
e,al
lcol
umnsi
nfor
mat
ionst
oredunder“
user
_tab_col
umns”dat
adi
cti
onar
y.
MUARLISI
R 2015
51

Cl
assi
fi
cat
ion:
Publ
ic
SQL>descuser _
tab_col
umns;
SQL>selectcol
umn_ namefrom user
_tab_columnswhere
tabl
e_name=‟EMP‟;
Q)Wr i
teaquerytodispl
aynumberofcol umnsf r
om emptabl
e?
Ans:SQL>selectcount(
*)f
rom user_
tab_columnswheretabl
e-name=‟
EMP‟
;

DEFAULT:I nOr acle,wecanal sopr ovide“ defaul t


”valuesf oracol umnusi ng“DEFAULT”const rai
nt.
Syntax:columnnamedat at
y pe( si
ze)def aultactual val
ue;
Eg:SQL>cr eatetableb1( namev archar (10),sal number (10)def ault5000);SQL>insert
i
ntob1( name)v alues( „
abc‟ );
SQL>sel ect*f rom b1;
NOTE:I nOr acle,ifyouwantt ov i
ewdef aul tvaluesforacol umnt henwear eusing“data_def
ault”
property(predef i
nedcol umn)f rom “ user _
tab_ columns”dat adictionary
.Eg: SQL>desc
user_t
ab_ columns;
SQL>sel ectcol umn_ name, dat a_defaul tfrom user _t
ab_ columnswher et abl
e_name=‟B1‟;
COLUMN_ NAME DATA_ DEFAULT
--
--
--
---
--
---
--
---
---
--
---
---
--
---
---
--
--
-----
-
SAL 5000
Adding( or)Droppi ngconst r aintsonexi stingt able:
I
nOr acle,wecanaddordr opconst rai
nt sonexi sti
ngtabl eusing“ ALTER”command.NOTE1: I
fwe
wantt oaddconst raintsonexi sti
ngt abl eorexi sti
ngcol umnt henwear eusing“tabl
elevelsynt
ax
method” .
Eg:SQL>al t
ertabl ea1
addpr i
mar ykey (sno) ;

NOTE2:Ifwewanttoaddanewcol
umnalongwit
hconst
rai
ntt
henwear
eusi
ng“
Col
umnl
evel
synt
ax
method”
.
Eg:
SQL>altert
abl
ea1addnamevar
char
2(10)uni
que;

MUARLISI
R 2015
52

Cl
assi
fi
cat
ion:
Publ
ic
Q)Addf
orei
gnkeyi
nexi
sti
nga2refer
encesa1?
Ans:
SQL>al
tert
abl
ea2addfor
eignkey(
sno)ref
erencesa1(
sno)
;

NOTE3:I fwewantt oadd“ NOTNULL”const


rai
ntsi
ntoexi
sti
ngt
abl
eorexi
sti
ngcol
umnt
henwear
e
usi
ng“ alt
erwithmodi fy
”.
Syntax:al
tertabl
et abl
enamemodi f
ycolumnnamenotnull
;
Eg:SQL>cr eatetablea3(snonumber(
10))
;
SQL>al t
ertablea3modi fysnonotnul
l;

Wri
teaquer
ytoaddnewcolumnwi t
hnotnul
lint
oa3?Ans:SQL>
al
tert
abl
ea3addnamevarchar
2(10)notnul
l
;

NOTE:InOr acle,whenev erwear ecopy i


ngat ablefr om anothertabl
econstrai
ntsarenevercopi
ed.But
i
nalldatabasesy stems“notnul l”constraintsonl ycopied.
Eg:SQL>cr eatet ablea4assel ect*f r
om a3; “not
null
iscopied”
SQL>desca4;
Eg:SQL>cr eatet abledept1assel ect*f rom dept ;SQL>
sel
ect*from dept 1;
SQL>altertabledept 1addpr i
mar ykey(dept no) ;
SQL>createt ableemp1assel ect*f rom emp;
SQL>select*f rom emp1;
SQL>altertableemp1addpr i
mar ykey(empno) ;
SQL>altertableemp1addf oreignkeydept nor eferencesemp1( deptno)ondeletecascade;
Droppi
ngConst r
aints:Bydroppi ng“Const raintname”t womet hodsfordroppi
ngconst r
aint
s.
Method1: Altertabletablenamedr opconst rai ntconst r
aintname;
OR
Method2:
Alt
ertablet ablenamedr oppr imarykey ;
Alt
ertablet ablenamedr opuni que(col1,col 2,….)
;

MUARLISI
R 2015
53

Cl
assi
fi
cat
ion:
Publ
ic
Dat
e:8/
4/15

SQL>cr eatetabletest(snonumber (
10)pri
marykey);SQL>
alt
ertabletestdroppr imar ykey;
NOTE:I nOracle,ifwewantt odr oppr i
marykeyalongwithreferencedf
oreignkeysthenweareusi
ng
“Cascade”clauseal ongwi t
h“Alterdrop”.
Syntax:alt
ertabletablenamedr oppr imar
ykeycascade; SQL>
alt
ertablea1dr oppr imar ykey;
Err
or:thisunique/primar ykeyisr efer
encedbysomef or
eignkey .
Soluti
on:SQL>al tertablea1dr oppr i
marykeycascade;
Eg:NotNul lconstraintsfordroppi ng.
SQL>desca3;
SQL>descuser _cons_ columns;
SQL> select col umn_ name, const
rai
nt_
name from user_cons_
columns where
tabl
e_name=‟ A3”;
COLUMN_ NAME CONSTRAI NT_ NAME
-
---
--
--
--
--
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
--
--
---
---
NAME SYS_ C005526
SNO SYS_ C005525
SQL>altertablea3dropconstraintSYS_C005526;
SQL>altertablea3dropconstraintSYS_C005525;
SQL>desca3;

SUBQUERY(
or)NESTEDQUERY:

Querywi thi
nanot herqueryiscal l
ed“ SubQuery”or“NestedQuer y”.Subquery‟sar eusedtor et
riev
e
dat
af r
om “ si
ngl e”or“ mult
iple”tablesbasedon“ Morethanonest epprocess”.Allrel
ationaldatabase
havi
ngt wot ypesofsubquer y‟s:
Non-Cor rel
at edsubquer y‟s
Correlatedsubquer y‟
s
I
nNon- correlatedsubquer y‟s“ chil
d”quer yisexecutedf irstt henonly“par ent”quer yisexecuted,
whereasi ncor relatedsubquer y‟s“parent”quer
yisexecutedf ir
stt henonly“chil
d”quer yisexecuted.
Non- Cor r
elat edsubquer y ‟s:Thesesubquer y‟
smai nlyconsi stoftwopar t
s.
I.Chi ldquer y
Par entquer y
ChildQuer y:Aquer ywhichpr ovidesvaluestotheanotherquer yiscal
l
ed“ ChildQuer yorInner
Quer y”.
ParentQuer y :Aquer ywhi chreceivesv al
uesfr
om anot herquer yiscal
led“Par entQueryorOut er
Quer y”.
I
nnon- cor r
elatedsubquer ymaxi mum l i
mitisupto“255”quer y‟s.

NON-CORRELATEDSUBQUERY:
Si
ngl
erowsubquer
y‟s
MUARLISI
R 2015
54

Cl
assi
fi
cat
ion:
Publ
ic
Mult
ipl
erowsubquery
‟s
Mult
ipl
ecol
umnsubquer y
‟s
I
nli
nevieworsubquer
y‟sareusi
ngi
n“f
rom”cl
ause.

Wr i
teaquer ytodispl
ayt heempl oyeeswhoaregetti
ngmor esalar
yt hantheav
g(sal
)fr
om emp?
Ans:SQL>sel ectename, salfr
om empwher esal
>(sel
ectavg(sal
)from emp) ;
Thisisa“Singlerowsubquer y”becauseherechil
dqueryret
urnssingl
ev alue.I
nSi
ngler
owsubquery‟
s
wear eusing=,<,
>,<=,
>=,betweenoper ators.
Executi
on:
Step1:SQL>sel ectavg(sal)fr
om emp;
2830.35714
Step2:SQL>sel ect*from empwher esal>2830.
35714

Wri
teaquerytodi
spl
aytheempl
oyeeswhoareworki
nginsal
esdepart
mentfrom emp,
deptt
ables.
Ans:SQL>sel
ectenamefr
om empwheredept
no=(sel
ectdept
nofr
om deptwher
edname=‟SALES‟)
;

Dat
e:9/
4/15

Wri
teaquerytodi
spl
aytheempl
oyeeswhoareworki
ngin“SMI
TH”depar
tmentnumberfr
om emp
tabl
e?
Ans:SQL>sel
ectenamefr
om empwheredept
no=(sel
ectdept
nofr
om empwhereename=‟
SMI TH‟
);

Q)Writ
eaquerytodi
spl
ayseni
ormostempl
oyeedetai
l
sf r
om emptabl
e?
Ans:
SQL>select*f
rom empwher
ehir
edat
e=(sel
ectmin(
hir
edat
e)f
rom emp)
;

Q)Writ
eaquerytodi
spl
ayhighestsaldet
ail
semptable?
Ans:
SQL>select*f
rom empwher esal
=(sel
ectmax(sal
)fr
om emp)
;

Wri
teaquer
ytodispl
ayhi
ghestpai
dempdepartment,
dnamefrom emp,deptt
ables?Ans:SQL>
sel
ectdnamefr
om deptwher
edeptno=(
sel
ectdept
nofrom empwheresal
=(sel
ectsal(
max)fr
om
emp));

Q)Writ
eaquerytodi
splaysecondmax(
sal
)from emptabl
e?
Ans:
SQL>selectmax(
sal)fr
om empwheresal<(
sel
ectmax(sal
)fr
om emp)
;

Q)Writ
eaquerytodi
spl
aysecondhi
ghestsalempl
oyeedetai
l
sf r
om emptable?
Ans:
SQL>select*f
rom empwheresal
=(sel
ectmax(
sal
)from empwheresal<(sel
ectmax(
sal
)fr
om
emp))
;

MUARLISI
R 2015
55

Cl
assi
fi
cat
ion:
Publ
ic
Wri
teaquer ytodi
spl
ayt
heemploy
eeswhoareworki
ngunder„
BLAKE‟fr
om empt abl
eusing
„empno,mgr‟columns?
Ans:SQL>select*fr
om empwher
emgr =(
sel
ectempnofr
om empwhereename=‟BLAKE‟);

Wr i
teaquer yt odisplaylowestaver
agesal
aryjobfr
om empt
abl
es?Ans:
SQL>sel ectjob,avg(sal)from emp
groupbyj ob
havingav g(sal
)=(sel
ectmi n(
avg(
sal)
)fr
om emp);Err
or:
nestedgr oupfunctionwi thoutGROUPBY

NOTE:Inall databasesy stemswheneverchil


dquer
ycontai
nsnestedgroupf
unct
ionsthenwemust
use“GroupBY”cl ausewi t
hinchil
dquer
y.Ans:SQL>sel
ectjob,
avg(sal
)fr
om empgroupbyjob
havi
ngav g(sal)
=( selectmin(av
g(sal
))f
rom empgroupbyjob);
JOB AVG( SAL)
--
--
--
--
--
--
--
---
--
---
--
--
SALESMAN 1050

Writ
eaquer ytodispl
aylowestav er
agesal
aryj
obfrom emptabl
ewher
edept
nol
esst
han30?
Ans:SQL>selectdeptno,min(sal
)from empgr
oup
bydeptno
havi
ngmi n(
sal)>(
selectmin(
sal)fr
om empwher edept
no=30);
DEPTNOMI N(SAL)
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
-
10 4400
20 1700

Dat
e:10/
4/15

Wri
teaquer ytodispl
ayjob,
avg(sal
)oftheempl
oyeeswhosejobav
g(sal
)mor
ethant
hecl
erk‟
sjob
avg(
sal)f
rom empt able?
Ans:SQL>selectavg(sal
),j
obfr
om empgr oupbyj
ob
havi
ngavg(sal)>(
selectavg(
sal
)fr
om empwher ej
ob=‟CLERK‟
);

NOTE:Inalldat
abases,wheneverwear eusingsubquery‟
salwaysdat
abaseser
versret
urnsparent
queryt
abl
ecolumns.i.
e.,
wear eunabl
etousechi l
dquer
ytablecol
umnsi
ntopar
entquer
ytoovercome
thi
sprobl
em wemustusej oi
nswithi
n“ParentQuery”
.

Wri
teaquer ytodi
spl
aytheemployeeswhoareworki
ngsalesdepart
mentf
rom emp,depttabl
es?
Ans:SQL>selectename,dnamef
r om empe,deptdwher
ee.deptno=d.
dept
noandd.dept
no=(sel
ect
dept
nofrom deptwheredname=‟SALES‟)
;
MUARLISIR 2015
56

Cl
assi
fi
cat
ion:
Publ
ic
ENAME DNAME
-
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
ALLEN SALES
WARD SALES
MARTIN SALES…….

Wr i
teaqueryt
odispl
ayt
heemploy
eeswhoaregett
ingmoresal
arythant
he„BLAKE‟sal
aryf
rom
empt able?
Ans:SQL>select*fr
om empwher
esal>(
sel
ectsal
from empwhereename=‟BLAKE‟
);

MULTI PLEROW SUBQUERY‟ S:


Whenev erchi
ldquer
yr et
urnsmulti
pleval
uesthosetypesofsubquery
‟ sar
ecall
ed„Mult
ipl
erowSub
Query‟s‟.
Wr i
teaquerytodispl
aytheemployeedetail
swhoar egett
ingmax(sal
)ineachdepar
tmentf
rom
empt able?
Ans:SQL>select*fr
om empwher esal
=(selectmax(sal
)fr
om empgroupbydept no)
;
Er
ror:singl
erowsubquer yret
urnsmorethanoner ow.

Thisi
sanmult
ipl
erowsubquerybecauseherequer
yret
urnsmul
ti
plev
alues.I
nmul
ti
pler
owsub
query
‟swear
eusing„i
n‟,
„al
l
‟,„
any‟operat
ors.

NOTE:I
nal
ldat
abasesy
stemswecanal
souse„
in‟oper
atori
nsi
ngl
erowsubquer
y‟s.

Sol
uti
on:SQL>sel ect*f r
om empwheresali
n(sel
ectmax(sal
)fr
om empgroupby
dept
no); OR
SQL>selectename, sal
,dept
nofr
om empwher
esal i
n(sel
ectmax(
sal
)fr
om empgroupbydept
no)
;

Wri
teaquer ytodi
spl
aytheemploy
eeswhoar
eworki
nginsalesorresearchdepart
mentf
rom emp,
dept
?
Ans:SQL>selectename,
deptnofr
om empwher
edept
noin(
selectdept
nof rom deptwher
e
dname=‟SALES‟ordname=‟RESEARCH‟)
;

Wri
teaqueryt
odispl
ayt
heemploy
eeswhoarewor
kingas“super
visor
s”(
manager
s)f
rom emp
tabl
eusi
ngempno,mgr?
Ans:SQL>sel
ect*fr
om empwher
eempnoin(
sel
ectmgrfr
om emp);

Wri
teaquer ytodi
splaytheempl
oyeeswhoar enotwor ki
ngas“ super
visor
s”
(manager
s)fr
om empusingempno,
mgr?
Ans:SQL>sel
ect*f
rom empwhereempnonoti
n(sel
ectnv
l(mgr
,0)fr
om emp);

MUARLISI
R 2015
57

Cl
assi
fi
cat
ion:
Publ
ic
Dat
e:11/
4/15

TOPNAnaly
sis:
Inl
i
nevi
ew
Rownum

I
nli
nev i
ew:Oracl
e7.
2int
roduced“I
nli
nev
iews”
.InInl
i
nev
iewswear
eusi
ng“
sub
quer
y‟s”inpl
aceoft
abl
enamewi t
hinpar
entquery
.

Gener all
y,inal ldat abasesy stemswear enotal lowedt ouse“ Or derBy ”cl auseinchi l
dquer y‟
s.To
over comet hispr oblem or acle7. 2introducedsubquer y
‟sinf r
om “from”cl ause.Theset y
peofquer y‟
s
areal socal l
edas“I NLINEQUERY‟ s”.
Gener all
y,inor aclewear enotal l
owedt ouse“ Ali
asname”i n“ wher e”condi ti
on.Toov ercomet hi
s
probl em al so wear eusi ng“ I
nlinev iews” .Whenev erwear eusi ng“ I
nlinev iews”t hi
saliasname
automat icallybehav eslikecol umnname, thenonl ythi
sal i
asnamewecanusei n“where”condit
ion.
Eg: SQL>sel ectename, sal,sal*12annsal from empwher eannsal>30000;
Error: ANNSAL: Inv ali
dIdenf i
er.
Solut i
on: SQL>sel ect*f rom( selectename, sal ,
sal
*12annsal f
rom emp)wher eannsal>30000;
ROWNUM:( Magi cCol umn)Rownum i sanPsuedocol umn(gener ali
sedcol umn)i tbehavesl i
kea
tabl ecol umn.Whenev erwear einstal
lingor acleserverthenaut omaticallysomepsuedocol umns
arecr eatedi ndat abase.These“ PseudoCol umns”bel ongstoal lt
ableswi t
hindatabase.Rownum
psuedocol umni susedt of i
lterthedata
wi thi
nat able.
Rownum i sapsuedocol umnwhi chaut omat ical
lyassignsnumber st oeachr owi natableatthetimeof
select ion.

SQL>selectrownum, enamefr
om emp;
ROWNUM ENAME
-
--
--
--
--
--
--
---
--
--
---
--
--
--
--
-
1 SMITH
2 ALLEN
3 WARD

General
l
y,r
ownum hav
ingt
empor
ari
l
yv al
ues.
Eg:SQL>sel
ectr
ownum,enamef
rom empwheredept
no=10;

ROWNUM ENAME
-
---
--
--
--
--
--
--
--
--
--
--
--
--
--
-
1 CLARK
2 KI
NG
MUARLISIR 201
5
58

Cl
assi
fi
cat
ion:
Publ
ic
3 XXX

Wri
teaquerytodispl
ayf
ir
strowfr
om empt
abl
eusi
ngr
ownum?Ans:
SQL>select*f
rom empwhererownum=1;

Wri
teaquer ytodispl
aysecondrowf
rom emptabl
eusi
ngrownum?Ans:
SQL>select*from empwhererownum=2;
Norowssel ect
ed
Gener
all
y,rownum doesn‟tworkwit
hmorethan“
1”+veint
eger
,i.
e.,
itwor
kswi
th<,
<=oper
ator
s.

Wri
teaquerytodispl
ayf
ir
stfi
verowsfr
om empt
abl
eusi
ngr
ownum?Ans:
SQL>select*f
rom empwhererownum<=5;

Wri
teaquer
ytodisplayfi
rstf
ivehighestsal
aryempl
oyeesf
rom empusi
ngr
ownum?Ans:
SQL>
sel
ect*fr
om(sel
ect*from empor derbysaldesc)wher
erownum<=5;

t
h
Wri
teaquerytodispl
ay5 hi
ghestsal
aryemploy
eefrom emptabl
eusi
ngr
ownum?Ans:
SQL>
sel
ect*fr
om(select*fr
om empor
derbysaldesc)wher
er ownum=5minus
sel
ect*fr
om(select*fr
om empor
derbysaldesc)wher
er ownum<=4;

Dat
e:16/
4/15

Wri
teaqueryt
odispl
ayr
owsbetween1to5from empt
abl
eusi
ng“
Rownum”
?
Ans:SQL>sel
ect*fr
om empwher
erownum bet
ween1and5;

Writ
eaquer yt odispl
ayrowsbetweento5t o9from t
abl
e?Ans:
SQL>sel ect*from empwher erownum between5and9;Nor ows
sel
ected
Sol
uti
on: SQL>select*fr
om empwhererownum <=9mi
nus
sel
ect*from empwher erownum<=5;

Wri
teaquer yt
odispl
aysecondr
ecor
dfrom empusi
ngr
ownum?Ans:
SQL>select*fr
om empwhererownum<=2
minus
sel
ect*from empwhererownum<=1;

Wr i
teaquer yt
odispl
aylasttworecor
dsf r
om emptabl
eusi
ngrownum?Ans:
SQL>sel ect*fr
om empwher erownum<=14
minus
sel
ect*f rom empwhererownum<=12;
Solut
ion:SQL>select*fr
om empmi nusselect*f
rom empwherer
ownum<=
MUARLISI R 2015
59

Cl
assi
fi
cat
ion:
Publ
ic
(
sel
ectcount
(*)
-2f
rom emp)
;

SQL>sel
ect*f
rom empwher
erownum>1;Norows
sel
ected
SQL>sel
ect*f
rom empwher
erownum>=1;Rows
sel
ected

NOTE:
Wheneverweareusingal
iasnameforr
ownum in“
INLI
NEVIEWS”t
hent
hatal
i
asnamewor
ks
wi
thal
lSQLoperat
orsbecauset
hatali
asnamebehav
esli
keatabl
ecol
umn.

Writ
eaquer ytodi
splaysecondrecor
dfrom empt
abl
eusing“r
ownum”ali
asname?
Ans:SQL>select*fr
om( sel
ectrownum r
,ename,j
ob,
sal
from emp)wher
er=2;
R ENAME JOB SAL
-
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
-
2 ALLEN SALESMAN 1400

NOTE:Ifwewantt odisplayallthecol umnsf rom thetabl


eusingr ownum ali
asnamethenwemustuse
tabl
e.st
ar(
*)i.
e.,{
e.*}alongwi t
hr ownum al iasnameaf t
erselect.Other
wisecreat
eanali
asnamefor
thetabl
eanduseal i
asname. *afterselectalongwi thr
ownum al i
asname.
SQL>select*fr
om(sel ectrownum r ,emp. *from emp)wherer=2;
OR
SQL>select*fr
om( sel
ectrownum r ,e.*from empe)wher er
=2;

Wri
teaqueryt
odispl
aysecond,
thi
rd,
fif
th,
seventh,
eight
hrowsfr
om emptabl
eusi
ngr
ownum al
i
as
name?
Ans:SQL>sel
ect*fr
om (
sel
ectrownum r
,e.*f
rom empe)whererin(
2,3,
5,
7,
8);

Wr
iteaquer
ytodi
splayr
ecordsf
rom 5t
o9f r
om emptabl
eusi
ngr
ownum al
i
asname?Ans:
SQL>sel
ect
*f
rom(sel
ectr
ownum r
,emp.*fr
om emp)wher
erbetween5and9;

Wri
teaqueryt
odispl
ayfi
rstandlastr
ecor
dsfrom empt
ableusingr
ownum ali
asname?
Ans:SQL>sel
ect*fr
om(sel
ectrownum r,
emp.*f
rom emp)wherer=1orr=(
sel
ectcount
(*)f
rom emp)
;

Wr i
teaqueryt
odispl
ayevennumberofr
ecor
dsfrom emptabl
eusi ngrownum al
iasname?
Ans:SQL>select*fr
om(sel
ectr
ownum r,
emp.*f
rom emp)whererin(sel
ectmod(r,
2)=0fr
om emp)
;
Sol
ution:SQL>sel
ect*fr
om(sel
ectr
ownum r,
emp.*f
rom emp)wher emod( r
,2)
=0;

Wri
teaquerytodi
spl
ayski
pfir
st5rowsfrom emptabl
eusi
ngr
ownum al
i
asname?Ans:
SQL>
sel
ect*fr
om (sel
ectr
ownum r
,emp.*f
rom emp)wherer>5;
MUARLISIR 2015
60

Cl
assi
fi
cat
ion:
Publ
ic
ANALYTI CALFUNCTI ONSar eusedi nINLI
NEVI EWS.
ANALYTI CALFUNCTI ONS:
Or acl
e8ii ntroduced“ Analyti
calFuncti
ons”.Thesefunct
ionsaresimil
arto“ Groupfunct
ions”butgroup
functionsr educesnumberofr owswi thinthegroup.Whereas“ Anal
yticalFuncti
os”doesn‟treduces
numberofr owswi thi nt hegroup.Thati swhenwear eusinganalyt
icalfuncti
onsdatabaseserv er
s
execut esforeachandev eryrowwi t
hinthegroup.
Usi ngGROUPf unct
ion.
Eg: SQL>sel ectdept no,avg(sal
)from empgr oupbydeptno;
DEPTNO AVG( SAL)
--
----
--
--
---
--
--
---
---
---
-
10 5883.3333
20 2935
30 1666.66667

Usi
ngAnaly
tical
Functi
ons
SQL>sel
ectdeptno,
avg(sal
)ov
er(
par
ti
ti
onbydept
no)f
rom emp;

Or
acl
ehavingf ol
lowi
ngAnal
yti
cal
funct
ions.
Row_number ()
Rank()
Dense_rank()

Thesethr
eeanal
yti
calfunct
ionsaut
omat
ical
l
yassi
gns“
ranks”t
oeachr
owi
nat
abl
eei
thergr
oupwi
se
orrowswisei
natable.

Dat
e:17/
4/15

Anal
yti
calFuncti
on:
Synt
ax:
Anal
yti
cal funct
ion name ov er(part
it
ion by col umnname or der by columnname[asc/desc]
);
Row_number()anal
yti
calfunct
ionaut omaticall
yassignsdi
ffer
entranknumberswhenv al
uesaresame.
Whereasrank()anddense_rank()analyt
icalfunct
ionsautomatical
l
yassignssameranknumberswhen
val
uesaresame.Andal sorank()skipsnextconsecut iv
eranknumber swhereasdense_r
ank()doesn‟t
ski
psnextconsecut
iveranknumber s.

Eg:row_number()
:
DEPTNO ENAME SAL R
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
20 SCOTT 3800 1
20 FORD 3800 2
20 JONES 3475 3
201
MUARLISI
R 5
61

Cl
assi
fi
cat
ion:
Publ
ic
Eg:rank()
:
DEPTNO ENAME SAL R
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
20 SCOTT 3800 1
20 FORD 3800 1
20 JONES 3475 3

Eg:dense_r
ank()
:
DEPTNO ENAME SAL R
-
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
20 SCOTT 38001
20 FORD 38001
20 JONES 34752

Wri
teaquerytodispl
ayhighestsalar
iest
olowestsalar
iesineachdepar
tmentfrom empt able
usi
ngrow_number()anal
yti
calfunct
ion?
Ans:SQL>sel
ectdeptno,ename,sal
,row_numberover
(part
iti
onbydeptnoorderbysaldesc)rfrom
emp;

nd
Wr i
teaquer ytodi
spl
ay2 hi ghestsalar
yemployeeineachdepar
tmentfr
om emptabl
eusing
analy
ticalf
unction?
Ans:SQL>sel ect*fr
om(selectdeptno,ename,sal
,dense_r
ank()ov
er(
part
it
ionbydept
noorderbysal
desc)rfrom emp)wherer=2;

t
h
Wri
teaqueryt
odispl
ay5 highestsal
aryempl
oyeef r
om emptabl
eusinganaly
tical
funct
ion?
Ans:SQL>sel
ect*fr
om(sel
ectdept
no,ename,sal
,dense_rank(
)ov
er(
orderbysal
desc)rfr
om emp)
wherer=5;

NOTE:
Inanal
yti
cal
funct
ions“
Par
ti
ti
onBy
”cl
ausei
sanopt
ional
clause.

Wri
teaquer yt
odispl
aynthhighestsalar
yemployeefr
om emptableusinganal
yti
calfunct
ion?
Ans:SQL>select*fr
om(sel
ectdeptno,ename,sal
,dense_
rank(
)ov
er(orderbysaldesc)
rfrom emp)
wherer=&n;

Output:
Enterval
uef orn:1
DEPTNO ENAME SAL R
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
-
10 KING 7900 1

MUARLISI
R 2015
62

Cl
assi
fi
cat
ion:
Publ
ic
ROWI D:
Rowi disanpseudocol umn,itbehaveslikeatablecolumnwhenev erwear einsert
ingdat aint
otabl
e
thenor acleser
verautomat i
call
ygeneratesanuni queident
if
icat
ionnumberf ori
dentif
yingar ecor
d
uniquely.Thisiscall
ed“ ROWI D”.General
ly
,usingr owi
d‟swecanr et
rievedat av er
yqui ckl
yfrom
database.
Gener al
ly,
rownum havi
ngt emporaryval
ueswhereasr owedhavingfi
xedvalues.Eg:SQL>
selectrownum,rowid,
enamef r
om emp;

Eg:SQL>selectr
ownum, r
owid,enamef r
om empwher
edept
no=10;
InOr
acl
e,
bydefaul
trowid‟
sareascendi
ngor der
.

Wri
teaqueryt
odispl
aysecondrecor
dfrom emptableusi
nganal
yti
calf
unct
ion,
rowid?Ans:sel
ect
*f
rom(
sel
ectdept
no,
ename,sal,
row_number(
)over
(orderbyr
owid)
rfr
om emp)wherer=2;

Wri
teaqueryt
odispl
ayeachdepar
tmentsecondr owfr
om emptabl
eusinganal
yti
calf
uncti
on,
rowi
d?
Ans:SQL>sel
ect*fr
om(sel
ectdept
no,ename,sal
,row_number
()ov
er(par
ti
tionbydept
noorderby
rowi
d)rfr
om empwherer=2);

Wri
teaquer yt
odispl
aylastt
worecordsf
rom emptabl
eusi
nganal
yti
calf
uncti
on,r
owid?
Ans:SQL>select*fr
om(sel
ectdept
no,ename,sal
,row_
number
()ov
er(or
derbyrowiddesc)rf
rom
emp)wherer<=2;

Dat
e:18/
4/15

Wecanal sousemax(),min(
)funct
ionsi
n“r
owi
d‟s”
.
Eg:SQL>selectmax(
rowid)fr
om emp;
SQL>selectmax(r
owid)fr
om emp;

Q)Writ
eaquerytodi
spl
ayfi
rstr
owfrom emptableusi
ngrowi
d?
Ans:
SQL>select*f
rom empwherer
owid=(sel
ectmin(
rowi
d)f
rom emp)
;

Q)Writ
eaquerytodi
spl
aylastr
ecor
dfrom emptabl
eusingrowi
d?
Ans:
SQL>select*f
rom empwhererowi
d=(sel
ectmax(
rowid)f
rom emp)
;

Wri
teaquer ytodisplaydupli
cat
edataf
rom t
hef
oll
owingt
abl
e?SQL>
createtabletest(snonumber (10)
);
SQL>i nsertintotestvalues(
&sno);Ent
er
valuesforsno: 10
Entervaluesf orsno:10
Entervaluesf orsno:10
Entervaluesf orsno:20
MUARLISI R 2015
63

Cl
assi
fi
cat
ion:
Publ
ic
Enterv
aluesforsno:20
Enterv
aluesforsno:30
Enterv
aluesforsno:40
SQL>select*fr
om test
;
SNO
--
--
-
10
10
10
20
20
30
40

SQL>selectsno,count
(*)f
rom t
estgr
oupbysnohav
ingcount
(*)
>1;
SNO COUNT(*)
-
--
--
--
--
--
--
---
--
--
--
--
--
--
3
2

Gener all
y ,
rowi d‟sar eusedi nsubquery‟
sf ordeleti
ngdupl i
caterowsinat abl
e.
Wr iteaquer yt odeletedupl i
caterowsex ceptoner owi neachgroupf r
om at ableusingr owid?
Ans: SQL>del etef rom testwher erowidnotin(selectmi n(
rowid)fr
om testgroupbysno) ;SQL>select*
from t est ;
SNO
--
---
10
20
30
40
Mul tipleCol umnSubQuer y‟s:
I
nal ldat abasewecanal socompar emul ti
plecolumnsoft hechil
dquer ywiththemul t
iplecolumnsof
thepar entquer ytheset ypeofquer y‟sarealsocal l
edas“ Multi
pleCol
umnSubQuer y‟s”.
I
nal l dat abasesy stemswhenwear eusingmul t
iplecolumnsubquer y‟sthenwemustspeci fyparent
quer ywher econdi t
ional column‟swi t
hinparanthesis“()”.
Sy ntax: select*( or)col1, col2,
….from t
ablenamewher e(col1,
col2,
…….)in(selectcol1,col2,
……f rom
tablenamewher econdition).

Wri
teaquer yt
odispl
ayt
heemployeeswhosejob,mgrmatchwi
ththej
ob,
mgroft
heempl
oyee
„SCOTT‟fr
om empt abl
e?
Ans:SQL>select*fr
om empwher
e(j
ob,mgr)i
n(sel
ectj
ob,mgrfr
om empwher
eename=
„SCOTT‟)
;
MUARLISIR 2015
64

Cl
assi
fi
cat
ion:
Publ
ic
Wri
teaquerytodi
spl
ayhighestsal
aryempl
oyeesi
neachdepart
mentfr
om emptabl
eusing
mult
ipl
erowsubquerys?
Ans:SQL>sel
ectdept
no,sal
,enamef r
om empwheresal
in(sel
ectmax(
sal
)fr
om empgroupby
dept
no);

DPETNO SAL ENAME


-
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
10 7900 KING
20 3800 FORD
20 3450 SCOTT
30 3450 BLAKE

Solution:
Wr i
teaquer ytodi
splaytheemployeeswhoar
egett
ingmaximum sal
aryi
neachdepar
tmentfr
om
empt ableusi
ngmul ti
plecolumnsubquery?
Ans: SQL>sel ectdeptno,sal
,enamefr
om empwhere(
deptno,
sal)i
n(sel
ectdept
no,
max(sal
)fr
om emp
groupbydept no);
DPETNOSALENAME
--
--
---
---
--
---
--
--
--
---
--
--
--
--
--
---
--
--
10 7900 KING
20 3800 FORD
30 3450 BLAKE

Wri
teaquerytodispl
ayseniormostemploy
eesineachjobfrom emptabl
eusi
ngmul ti
plecolumn
subquery
?
Ans:SQL>sel
ecthir
edate,ename,j
obfrom empwhere(hi
redat
e,job)i
n(sel
ectmi
n(hi
redate),
jobfrom
empgroupbyjob);

Wri
teaquer ytodisplayename, dname, saloftheempl
oyeeswhosesal ,comm mat
chwitht
hesal
,
comm.Oft heempl oy
eeswor kingint helocati
on„DALLAS‟?
Ans:SQL>selectename, dname, salfrom empe, deptdwheree.
deptno=d.dept
noand
(sal
,
nvl
(comm, 0))i
n(selectsal,
nv l
(comm, 0)from empwheredeptno=(
selectdept
nofr
om dept
whereloc=‟
DALLAS‟ )
);

Dat
e:20/
4/15

Writ
eaquer yt
odispl
ayt
heemployeewhoareget
tingmoresal
aryt
hanthehighestpai
dempl
oyee
t
h
i
n20 depar t
mentf r
om emptabl
e?
Ans:SQL>select*fr
om empwheresal
>(sel
ectmax(
sal)f
rom empwheredept
no=20);

t
h
Wri
teaquer yt
odispl
ayt
heemploy
eeswhoaregett
ingmor et
hant
helowestpai
dempi
n10 dept?
Ans:SQL>select*fr
om empwher
esal>(
sel
ectmin(
sal
)from empwheredept
no=10);
MUARLISIR 2015
65

Cl
assi
fi
cat
ion:
Publ
ic
Whenev erresoucet abl
ehav inglargeamountofdat aandalsochi l
dquerycontai
nsmax( )ormin(
)
functi
onsandal sowhenwear ecompari
ngthenthosetypeofsybquery
‟sdegr
adesperfor
manceofthe
appli
cati
on.Toov ercomet hi
spr obl
em toimprov
eperformanceofthesety
peofquery‟sANSI/I
SOSQL.
Thesear e“all
”,
”any”.Thesesubquer y‟
sspecialoper
atorsareusedalongwit
hr el
ati
onaloper
ator
sin
parentquer
y“ where”conditi
on.

SQL>sel
ect*f
rom empwheresal>all
(sel
ectsal
from empwheredept
no=20)
;SQL>sel
ect*
fr
om empwheresal>any
(sel
ectsal
from empwher edept
no=10)
;

SubQuer ySpeci alOper atorsareusedi nMul ti


pl eRowSubQuer y:
Whenchi ldquer yr eturnsmul t
iplev aluest hent hoset ypesubqueryar ecall
ed“ Mul
ti
pleRow Sub
Query‟s”.Inal ldatabasesy stems“ i
n”,”
all”
,“any ”operat
orsusedin“Multi
pleRowSubQuer y
‟s”.
In-
>Itreturnssamev aluesint hel i
st(
childquer y)
All
->Itsatisfiesallv aluesint helist
Any->Itsat i
sf i
esanyv al
uei nthel i
st
I
N- >=ANY
Wr i
teaquer ytodi splaytheempl oyeeswhoar egett
ingmorethantheallsal
ari
esofthecler
ksf
rom
empt ableusi ngsubquer yspeci aloperator?
Ans:SQL>sel ect*f rom empwher esal>all(
sel ectsalfr
om empwher ejob=‟CLERK‟)
;
Todi splayt her esultinorder(asc/desc)

SQL>sel
ect*f
rom empwher
esal
>al
l
(sel
ectsal
from empwher
ejob=‟
CLERK‟
)or
derbysal
desc;

Note:whenev erweareusi
ngsubqueryspecial operat
or“OR”int
ernal
lydatabaseserversusesl
ogical
operat
or“ AND”
Eg:SQL>sel ect*f
rom empwheredeptno>al
l(10,20);
Output:30
Note:Whenev erweareusi
ngsubqueryspecial operat
or“ANY”inter
nall
ydat abaseserv
erslogi
cal
l
y
operat
or s“OR”
Eg:SQL>sel ect*f
rom empwheredeptno>any(10,20);
Output:20
30
NOTE: “
=any ”isal
sosameas“in”oper
atorbut“ <>any”isnotsameas“ notin”operat
or.
Eg:SQL>sel ect*f
rom empwheredeptnonoti n(10,
20)
Output:30

SQL>sel
ect*fr
om empwher
edept
no<>any
(10,
20)
;Output
:
10
20
30
MUARLISIR 2015
66

Cl
assi
fi
cat
ion:
Publ
ic
NOTE:“<>al
l”isal
sosameas“noti
n”operat
or.
Eg:SQL>select*fr
om empwheredept
nonotin(10,
20)
;
SQL>select*from empwher
edeptno<>al
l(
10,
20);

CORRELATEDSUBQUERY‟ S:
InNon-Cor
rel
atedsubquer y
‟ s„chil
dquer y‟isexecut edf ir
stt henonl y„ par
entquery‟i sexecuted.
Whereasincorrelat
edsubquer y‟s„parentquer y
‟isexecut edf ir
stthenonl y„chi
ldquery‟i sexecut
ed.
Wheneverwear esubmi t
ti
ngcor relatedsubquer ythendat abaseser versgetacandi dater owf r
om the
„par
entquery
‟t ableandt hencont r
olpassedi nto„ chil
dquer y
‟wher econdi ti
onandt henbasedon
eval
uat
ionvalueitcompar ewi t
h„ parentquery‟wher econdi tion.Generall
y ,i
nnon-corr
elatedsubquer y
„chi
l
dquery‟i
sexecut edonlyonceper„ par
entquer y‟tablewher easincor relat
edsubquer y .
„Chi
ldquer
y‟isexecut edforeachr ow for„parentquer y‟t able.Inalldatabasesy st
emsi ncorrel
ated
subquerywemustcr eatealiasnamef or„parentquer y
‟t ablewi thi
n„ parentquery‟anduset hatal
ias
nameinchil
dquer y“wherecondi t
ion”.

Synt
ax:sel
ect*fr
om tabl
enameal i
asnamewhencolumnname=(
sel
ect*f
rom t
abl
enamewher
e
col
umnname=(anyoper
ator
)ali
asname.col
umnname)
;

General
ly
,cor
relat
edsubqueryareusedindenormali
zat
ionprocessi
ndenormal
izat
ionprocessi
nt hi
s
processweareusi ngcor
rel
atedupdates.Gener
all
y,i
fyouwantt omodifyonetablecolumnvalues
basedonanothertabl
eandalsothoset
ablesarer
elat
edthenonlyweareusi
ng“Correl
atedupdat
e”.

Syntax:
updat
etabl
ename1aliasname1setcolumnname=(selectcolumnnamef r
om t
ablename2
al
iasname2whereal
iasname1.commoncol name);
SQL>altert
ableempadddnamev archar
2(10);
SQL>updateempesetdname=( sel
ectdnamef r
om deptdwheree.deptno=d.
dept
no)
;SQL>sel ect*
fr
om emp;

Dat
e:21/
4/15

Wr i
teaqueryt
odisplayt
heemployeeswhoaregett
ingmoresal
aryt
hantheaveragesal
ari
esof
thei
rjobfr
om empusi ngcor
rel
eat
edsubquery?
Ans:SQL>select*fr
om empewher esal>(
sel
ectavg(
sal)f
rom empwherej
ob=e.
job);

MUARLISI
R 2015
67

Cl
assi
fi
cat
ion:
Publ
ic
Non-
Cor
rel
atedSubQuer
y:

Cor
rel
atedSubQuer
y:

Wri
teaqueryt
odispl
ayfi
rsthi
ghestsal
aryemployeefr
om emptabl
eusi
ngcorr
elat
edsubquer
y??
Ans:SQL>sel
ect*fr
om empe1wher e1=(sel
ectcount(
*)fr
om empe2wheree1.
sal
>=e2.
sal
);
Output
:ki
ng 7900

Writeaquer ytodi
spl aysecondhighestsal
aryemploy
eefrom f
oll
owi
ngt
abl
eusi
ngcor
rel
atedsub
query?
Ans:SQL>cr eatetabl
et est(enamevarchar
(20)
,salnumber(
10))
;SQL>
i
nsertintotestval
ues(„&e‟,&s);
Entert
hev aluesfore:abc
Entert
hev aluesfors:100
SQL>/
Entert
hev aluesfore:xyz
Entert
hev aluesfors:150
SQL>/
Entert
hev aluesfore:zzz
Entert
hev aluesfors:200
SQL>/
Entert
hev aluesfore:bbb
Entert
hev aluesfors:300

SQL>sel
ect*f
rom t
est
;
ENAME SAL
MUARLISI
R 2015
68

Cl
assi
fi
cat
ion:
Publ
ic
--
--
--
--
--
--
--
--
--
--
--
--
abc 100
xyz 150
200
bbb300

SQL>sel
ect*f
rom t
este1wher
e2=(
sel
ectcount
(*)f
rom t
este2wher
ee2.
sal
>=e1.
sal
);

Execut
ionProcess:
Phase1:
Step1:geta“Candi
dateRow”[ wher
ecur
sorpointerpoi
ntsar
ecor
discal
l
ed“
Candi
dat
eRow”
](abc100)
Step2:sel
ectcount(
*)from t
este2wher
ee2.sal>=100;
4
Step3:sel
ect*from e1.Where2=4;
Fal
se

Phase2:
Step1:geta“Candi
dateRow”[ wher
ecur
sorpointerpoi
ntsar
ecor
discal
l
ed“
Candi
dat
eRow”
](xy
z150)
Step2:sel
ectcount(
*)from t
este2wher
ee2.sal>=150;
3
Step3:sel
ect*from e1.Where2=3;
False

Phase3:
Step1:geta“ Candi
dateRow”[ wher
ecur
sorpointerpoi
ntsar
ecor
discal
l
ed“
Candi
dat
eRow”
](zz
z200)
Step2:selectcount(
*)from t
este2wher
ee2.sal>=200;
2
Step3:select*from e1.Where2=2;
Tr ue

Out
put
:zzz 200

NOTE:Whenev err esourcetabl


ehav i
ngduplicat
edat
abasedonwher econdit
ionalcol
umnt henthe
abovequerydoesn‟ tret
urnanyrows.Toov er
comethi
sprobl
em wemustuse“DISTINCT”cl
ausewit
hin
“Count(
*)”function.
Eg:SQL>insertintotestval
ues(
„mural
i
‟,200)
;SQL>
sel
ect*from test;
ENAME SAL
--
--
--
--
--
--
--
---
--
--
---
abc 100
xyz 150
MUARLISI R 2015
69

Cl
assi
fi
cat
ion:
Publ
ic
200
bbb300
murali
200

SQL>select*from t
este1wher
e2=(selectcount(
*)fr
om teste2wher
ee2. sal
>=e1.
sal
);
NoRowsSel ected
Sol
ution:
SQL>select*f rom t
este1where2=(selectcount
(di
sti
nct(
sal
))f
rom teste2where
e2.
sal=e1.
sal)
;
Output:
Zzz 200
Murali200

NOTE:Wecanalsowr i
teabov
equer
yusi
ng“n-
1”met
hod.I
nthi
scasewear
enotal
l
owedt
ouse“
=”
oper
atori
n“Where”condi
ti
onof“
Chi
ldQuer
y”.

Eg:SQL>select*f
rom t
este1wher
e(2-
1)=(
sel
ectcount
(di
sti
nct
(sal
))f
rom t
este2wher
e
e2.
sal>e1.
sal)
;

Writ
eaquer yt
odispl
aynt
hhi
ghestsal
aryemployeef
rom emptabl
eusing“Cor
rel
atedSubquer
y”.
?
Ans:SQL>select*fr
om empe1wher
e&n=( sel
ectcount
(di
sti
nct
(sal
))f
rom empe2wher e
e2.
sal>=e1.
sal)
;

Dat
e:22/
4/15

ExistsOper ator:Exist
soper atorusedin“ Correlatedsubquer y
‟s”.ExistsOperatorperf
ormanceisv ery
high.Compar eto“ i
n”oper at
or.Exist
soper atoral waysret
urns“ BooleanValues”eit
her“tr
ue”or“fal
se”.
ExistsOper atorisusedi n“where”conditionoft he“ParentQuer y”onlyandal sowhenwear eusing
ExistsOper at
ort henwear enotallowedtouse“ Col
umnName”al ongwith“Exist
sOperator”i
n“Wher e”
Condi t
ion.
Syntax:
Select * f rom t ablename al i
asname wher e exists(select * f r
om t abl
ename wher e
columnname=al iasname.Col umnname) ;
Inalldat abasesy stemsi fwewantt ot estwhet heronet abl
ev aluesareav ail
abeornotav ai
labei n
anothert abl
ecol umnst henonl yweareusi ng“ Exist
sOperator”.

NOTE:Exist
sOper at
orisusedtotestwhetheragi
venseti
sempt y(or
)non-
empt
yExi
stsonnon-
empt
y
setr
etur
ns“true”whereasexi
stsoperat
oronemptysetret
urns“
false”
.
Eg1:exi
sts{1,2,
3}=tr
ue
Eg2:exi
sts{ }
=f al
se

Wri
teaquerytodisplaythosedepar
tment
sfr
om deptt
abl
ehav
ingempl
oyeesi
nempt
abl
eusi
ng
cor
rel
atedsubqueryexistsoperat
or?
MUARLISIR 2015
70

Cl
assi
fi
cat
ion:
Publ
ic
Ans:SQL>select*fr
om deptdwhereexi
sts(
sel
ect*fr
om empwher
edept
no=d.
dept
no)
;
Output:
DEPTNO DNAME LOC
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO

Writ
eaquer ytodispl
aytheempl oyeeswhoar egetti
ngsamesal
aryasscottsal
aryf
rom emptabl
e
usingcor r
elat
edsubquer yexist
soperatorfr
om emp?
Ans: SQL>select*from empe1wher eexi
sts(sel
ect*from empe2whereename=‟SCOTT‟and
e2.sal=e1.
sal);
Output :
EMPNO ENAME JOB MGR HI REDATE SAL COMM DEPNTO
--
--
---
---
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
---
--
--
---
7902 FORD ANALYST 756603-DEC-81 3000 20
7788 SCOTT ANALYST 756619-APR- 87 3000 20

Fornotdi
spl
ayi
ng„
SCOTT‟i
ntheout
putt
abl
e:

Sol
uti
on:SQL>sel
ect*f
rom empe1wher
eexi
sts(
sel
ect*f
rom empe2wher
eename=‟
SCOTT‟and
e2.
sal
=e1.sal
);

Output:
EMPNO ENAME JOB MGR HI REDATE SAL COMM DEPNTO
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
7902 FORD ANALYST 756603- DEC-81 3000 20

Wri
teaquer yt
odi spl
aythosedepar
tmentsfr
om deptt
abl
edoesn‟
thaveemploy
eesinempt
abl
e
usi
ngcorrel
atedsubquer y?
Ans:SQL>select*from deptdwherenotex
ists(
sel
ect*fr
om empwheredept
no=d.
dept
no);
Output
:40oper at
ions boston

Wr i
teaquerytodisplayt
hosedepar
tmentdoesn‟
thaveempl
oyeesi
nempt
abl
eusi
ngnon-
cor
relatedsubquery‟s?
Ans:SQL>select*from deptwher
edeptnonotin(
sel
ectdept
nof
rom emp)
;
Output:40operat
ions boston

General
ly,
“notin”operat
ordoesn‟tworkwi
thnullval
uestoover
comethi
spr
obl
em wear
eusi
ng“
not
exi
sts”operat
oralongwith“cor
rel
atedsubquery”
.
SQL>select*from emp;
SQL>select*from deptwheredeptnonoti
n(sel
ectdeptnof
rom emp)
;
MUARLISIR 2015
71

Cl
assi
fi
cat
ion:
Publ
ic
NoRowsSelect
ed
SQL>sel
ect*fr
om deptdwher
enotexi
sts(
sel
ect*f
rom empwher
edept
no=d.
dept
no)
;Out
put
:40
Oper
ati
onsBOSTON

Dat
e:23/
4/15

NOTE:I nOracl
e,wheneverwear etest
ingonet abl
ecolumnv aluesar
eav ai
labl
e(or
)notavai
labl
ein
anothertabl
eusi
ngnotcorrel
atedandcorrel
atedquery‟
s.Thesetypeofquery
‟sareal
socal
ledas“Ant
i
Joi
ns”.
Eg:SQL>select*f
rom deptwheredeptnonotin(sel
ectdept
nofrom emp);

VI
EWS
View i
sandat abaseobjectwhichi susedtopr ovi
deaut
horit
ylevelofsecur
ity
.Generall
y,v
iewsar e
cr
eatedby“ DatabaseAdmi ni
str
ator”.
Viewdoesn‟ tstor
edat at
hat‟
swhyv iewisal
socalledas“
Virt
ualtabl
e”.Vi
ewisalsocal
ledas“Window
ofatable”
.
General
lyv i
ewsar ecreat
edfrom “Basetabl
es”.Basedonthetypeofbasetabl
esv i
ewsarecat
egorized
i
ntotwov iews.
Si
mpl eView
Compl exview(or)Joinvi
ew


Simpl
evi
ew”isaviewwhi
chiscreatedfr
om onl
y“OneBase”t
abl
eswher
eas“
Compl
exv
iew”i
sav
iew
whi
chi
screat
edfr
om “Mul
ti
plebase”tabl
es.

Simpl
eView:
Synt
ax:cr
eat
eorrepl
acev
iewviewnameas
sel
ect*fr
om t
abl
enamewherecondit
ion;

DMLOper ati
onsperformedonSi mplevi
ew:
WhenaSi mpleviewcont ains“Groupfunctions”,“Groupby ”
,”Rownum” ,“Di
sti
nct
”,“
SetOperat
ors”
,
“Joi
ns”thenwecannotper for
m DMLoper ationt hr
ough“ Simpleview”to“Basetabl
e”.
Wemusti ncl
ude“ Basetable”notnullcolumni nt
ot hev i
ew thenonlywecanper for
m“ I
nsert
ion
operat
ion”t
hrough“View2”baset abl
e.Otherwiseor acl
eser v
erreturnsanerror.

Eg1:SQL>cr eateorrepl
aceviewv
1asselect*fr
om empwheredept
no=10;
SQL>sel
ect
*fr
om v1;
SQL>inserti
ntov 1(
empno,ename,
dept
no)val
ues(1,
‟mur
ali
‟,
30)
;1row
cr
eated
SQL>select*from emp;

MUARLISI
R 2015
72

Cl
assi
fi
cat
ion:
Publ
ic
Eg2: SQL>cr eateorr eplacev iewv 2assel ectename, sal,dept nof r
om empwher edeptno=10;
SQL>sel ect*f rom v 2;
SQL>i nsertintov 2(ename, sal,deptno)v alues( „
abc‟ ,
1000, 30);Error
:
Cannoti nsertnullint oempno.
InOr acle,whenev erwear eusi ng“Gr oupf unct i
ons”or“ rownum”i nav iewt henwemustcr eateal
i
as
namef ort hoseexpr essionsot herwiseor acl eserverr eturnsaner ror.
Eg: SQL>cr eateorr eplacev iewv 3assel ectdepnt o,max( sal)af r
om empgr oupby
dept no;
Viewcr eated
SQL>sel ect*f rom v 3;
SQL>cr eateorr epl acev iewv 4assel ectrownum, enamef rom emp; Error:
mustnamet hisexpr essionwi t
hcol umnal ias.
SQL>cr eateorr epl acev iewv 4assel ectrownum r no, enamef r
om emp; SQL>
select*f rom v 4;
Inev erydat abasesy stemswhenev erwear ecreatingav iewt henaut omat icall
yvi
ewdefini
ti
ons
(SELECTSTATEMENTS……. )ar eaut omat icallypermanent lyst oredindat abase.
InOr acle,ifwewantt oviewt hesedef i
nit
ionst henwear eusi ng“ user_
v i
ews”dat adi
cti
onary.
Eg: SQL>descuser _v i
ews;
SQL>sel ectt extfrom user _viewswher ev iew_ name=‟ V3‟ ;
Out put:
TEXT
--
--
----
---
---
--
----
---
--
--
---
-----
---
---
--
---
----
--
--
--
-----
--
--
-----
--
-
selectdept no,max( sal)af rom empgr oupbydept no;

Dat
e:24/
4/15

ComplexView:Compl exv i
ewisav i
ewwhichi
scr
eat
edf
rom mul
ti
plebaset
abl
es.
Eg:SQL>creat
eorr eplacev iewv5
as
sel
ectename, sal,dname,l
oc
fr
om emp,dept
whereemp.dept no=dept.
deptno;
SQL>select*fr
om v 5;

DMLOper ati
onsonCompl exVi ews:
Eg:SQL>updat ev 5setename=‟ abc‟whereename=‟SMITH‟;1row
updated
SQL>updat ev 5setdname=‟ xyz‟wher edname=‟SALES‟;
Err
or:Cannotmodi fyacolumnwhi chmapstoanonkeypr eserv
edtabl
e.
General
ly,inalldat
abasesy stemswecannotper form DMLoperati
onst
hrough“
Compl
exVi
ews”t
o
basetables.Ifwearetrytoper f
or m DMLoperati
onsthensomet abl
ecol
umns
MUARLISI R 2015
73

Cl
assi
fi
cat
ion:
Publ
ic
areeffectedandsomeot hertabl
ecolumnsar enotef f
ected.InOracl
e,ifwewantt o“v
iew”ef
fect
ed,
unaff
ectedcol umnsthenwear eusing“user
_updatabl
e_columns”datadicti
onar
y.
Eg:SQL>descuser _updatabl
e_columns
SQL>sel ectcolumn_name,updatabl
efrom user
_updatable_col
umnswher etabl
e_name=‟
V5‟;

I
nOracle,al
sowecannotperfor
m DMLoperat
ionsthroughComplexVi
ewst
obaset
abl
etoov
ercome
t
hispr
oblem Or
acl
e8.0int
roductedi
nst
eadoft
rigger
sinpl/SQL.

TRI
GGERS:(
PL/
SQLconcept
)
Tri
ggersisalsosameas“ StoredProcedures”andal
soi
twil
laut
omatical
l
yinvokedwhenev
eraDML
operati
onsperformedonat able.Al
ldatabasesyst
emshav
ing2typesoftri
ggers.
Statementlevelt
rigger
s
Rowl ev
el t
rigger
s

I
nSt atementl evel t
ri
gger,tri
ggersbodyi sexecut
edonlyonceperDMLst atement
s.
Wher easinRowl evertr
igger,tr
iggersbodyisexecutedf
oreachrowf orDMLstat
ement
s.
Syntax:
Createorreplacetriggert
riggernamebef or
e/aft
er
Tri
ggerspeci
fi
cat
ion
I
nsert/Update/Deleteontablename[ foreachrow]-
--
--

rowleveltr
igger

begin
--
--
--
Tr
iggerbody
--
--
--
--
--
--
end;

DifferenceBet weenSt atementl evelandRowl


evelTr
igger
s:
Eg: SQL>cr eatetabletest(col1date);
Statementl eveltrigger:
SQL>cr eat
eorr eplacetriggertv1
afterupdateonemp
begin
i
nser tintotestvalues(sysdate);
end;
/

Testi
ng:
SQL>updat
eempsetsal
=sal
+100wher
edept
no=10;
3rows
updated

MUARLISI
R 2015
74

Cl
assi
fi
cat
ion:
Publ
ic
SQL>sel
ect*from t
est;
SQL>del
etefr
om test;
SQL>del
etetr
iggert
v1;

Rowl evelt
ri
ggers:
SQL>cr eateorr
eplacetri
ggert
v2
afterupdat
eonemp
foreachrow
begin
i
nser ti
ntot
estvalues(
sysdat
e);
end;
/

Testi
ng:
SQL>updat eempsetsal=sal
+100wher
edept
no=10;
3rows
updated
SQL>sel ect*fr
om t
est
;
SQL>dropt ri
ggert
v2;
Output:
COL1
--
--
--
24-APR-15
24-APR-15
24-APR-15

RowLev elTriggers:
I
nRowl eveltri
ggers,t
riggersbodyi
sexecutedpereachrowf orDMLst atement
s.That‟
swhywear e
usi
ng“ f
oreachr ow”clausewithi
ntri
ggerspeci
fi
cat
ionandalsoDMLt ransacti
on“r
ollback”segment
qual
ifiers.Thesear eol
d, new.
Thesequal i
fi
ersar eusedi nei
theri
ntri
ggerspeci
fi
cat
ionorint r
iggerbodywhenwear eusingthese
qual
ifiersintri
ggerbodyt henwemustuse“ :
”(col
umn)inf
rontofthe“Qual i
fi
ername”
.
Syntax:
:
old.
col umnname
Syntax:
:
new. columnname

MUARLISI
R 2015
75

Cl
assi
fi
cat
ion:
Publ
ic
Dat
e:25/
4/15

Wri
teaPL/ SQLr owleveltr
iggeronempt abl
ewhenev
eruserdel
eti
ngdat
athenaut
omat
ical
l
ythose
deletedrecordsar estor
edi nanothertable?
Ans: SQL>cr eatetablet
estassel ect*from empwhere1=2;SQL>
select*from test;
SQL>desct est;
SQL>cr eateorr eplacet
riggertg1after
deleteonemp
foreachr ow
begin
i
nser
tint
otestv
alues(
:ol
d.empno,
:ol
d.ename,
:ol
d.j
ob,
:ol
d.mgr
,:ol
d.hi
redat
e,:
old.
sal
,:
old.
comm,
:ol
d.dept
no)
;
end;
/
Viewcr eated
Test i
ng:
SQL>del etefrom empwher
esal
>2000;
SQL>
select*from test
;
10r owselected

InsteadofTr i
gger:
Gener all
y ,wecannotper f
orm“ DMLoper ati
ons”throughcompl exvi
ew t
o“Basetabl
e”.Toover
come
thispr oblem Oracl
e8.0introduced“ I
nsteadoft r
igger”i
nPL/ SQL.Bydef
aul
t“I
nst
eadofTr i
gger
s”ar
e
“Rowl ev erTri
ggers”
.“I
nsteadoft r
igger”arecreat
edon“ Views”.
Synt ax:
Creat eorr epl
acetri
ggertr
iggername
i
nst eadofi nsert
/update/
deleteonv i
ewname
foreachr ow
begin
--
---
--
--
---
--
--
---
--
end;

Eg:“I
nsteadofTri
gger
”:
SQL>createorrepl
acetr
iggertj
1
i
nsteadofupdateonv5
foreachrow
begin
updatedeptsetdname=:
new.dnamewher edname=:
old.dname;
updat
e
deptsetloc=:
new.l
ocwhereloc=:
old.
loc;
end;
/
MUARLISI R 2015
76

Cl
assi
fi
cat
ion:
Publ
ic
Tri
ggercreated
Testi
ng:
Ex1:SQL>updat ev5setdname=‟ xy
z‟wheredname=‟ SALES‟;
Rows
updated
Ex2:SQL>descuser _updatabl
e_col
umns;
SQL>selectCOLUMN_ NAME, UPDATABLEfrom user
_updatabl
e_col
umnswher
etabl
e_name=‟
V5‟
;
COLUMN_ NAMES UPDATABLE
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
-
ENAME YES
SAL YES
DNAME YES
LOC YES

SQL>updat
ev5setl
oc=‟
newy
ork‟wher
eloc=‟
DALLAS‟
;

MATERI
ALI
ZEDVI
EWS:
Oracle 8ii ntroduced “Mat er
ial
i
zed v i
ews”.These v i
ews ar e created by dat abase admini str
ator
.
“Mat eri
ali
zedv i
ews”ar eusedi ndatawar ehousingappli
cat
ions.Gener ally,v
iewsdoesn‟ tstor edata
wher e as “ Materi
ali
zed v i
ews”st or
e dat a.Generall
y,“Mat er
ial
ized v i
ews”ar e used toi mpr ove
performanceoft he“ Joined”or“ Aggregatabl
eQuer y
‟s”.“
Mat eri
ali
zedv iews”st oresrepl
icati
onoft he
remot edatabasei ntolocal node.“Materi
ali
zedviews”stor
esdat asamel ikeat able,butwhenev erwhen
wear eref
reshing“Mat erial
izedviews”itsynchr
onizesdatabasedon“ BaseTabl e”.
Syntax:
createmat erial
izedviewv i
ewname
assel ectstatement;

Di
ff
erenceBet
weenVi
ews,
Mat
eri
ali
zedVi
ews:

VI
EWS MATERI ALIZEDVI EW
1.Viewsdoesn‟
tstoredata 1.Mat erial
i
zedv i
ewst oresdata.
2.Secur
it
ypurpose 2.I mproveperformancepurpose
3.Whenwear edroppingbaset
abl
e 3. I
fwear edropping“Baset
abl
e”
al
so Mat eri
ali
zed view can be
accessi
ble.
4.Wecanper
for
m DMLoper
ati
ons 4. We cannotper for
m DML
onv
iews operat
ionsonMat eri
ali
zedv i
ews

Before we are cr
eati
ng Materi
ali
zed v
iew then Dat
abase Admini
str
atormustgi ve“Creat
e any
Material
izedvi
ew”pri
vi
legetouser
.Other
wiseoracl
eserv
erret
urnsanerr
or“I
nsuf
fi
cientPr
ivi
l
ege.
Syntax:
Grantcreateanymater
ial
izedvi
ewtousername;

MUARLISI
R 2015
77

Cl
assi
fi
cat
ion:
Publ
ic
Eg:SQL>connscot t
/tiger
SQL>cr eatemat eri
alizedviewmn1
as
sel
ect*f rom emp;
Err
or :Insuffi
cientPrivil
eges.
Solution:
SQL>connsy sassy sdba
Enterpasswor d:sys
SQL>gr antcreateanymat eri
ali
zedv
iewt
oscot
t;
SQL>connscot t
/ti
ger
Connect ed
SQL>cr eatemat eri
alizedviewmn1
assel ect*f r
om emp;
Mat eri
alizedVi ewCr eated.

Dat
e:27/
4/15

InOr acle,oneoft hemat erial


izedv i
ewbaset ablemustcont ainapr imarykey ,otherwiseoracl
eserv
er
returnsaner ror .
Eg: SQL>cr eat et abletest(snonumber (10));SQL>
createmat er i
alizedv i
ewmw1
as
sel
ect*f rom test;
Error:Insufficientpr i
vil
eges
SQL>connsy sassy sdba/ sys
SQL>gr antcr eat eanymat eriali
zedviewt oscot t
;
Gr antsucceeded
SQL>connscot t/ti
ger
SQL>cr eatemat eriali
zedv i
ewmw1
assel ect*f rom t est;
Error:table„ TEST‟doesnotcont ainapr i
mar ykeyconstraint
SQL>cr eatet abl ebase( snonumber (
10)pr i
mar ykey,namev archar2(20));
SQL>i nser tint obasev alues( &s,‟
&n‟);
SQL>sel ect*f rom base;
SQL>commi t;
SQL>cr eateorr epl acev i
ewv 1
assel ect*f rom base;
SQL>cr eat emat eri
ali
zedv i
ewmv 1
assel ect*f r
om base;
Her e,mat erializedv i
ewal sobehav eslikeav i
ewt hati
sint hiscasemat eriali
zedv iewisalsosameas
“View” .Thati swhenev erwear ecr eati
ngmat eri
ali
zedv i
ew t henaut omat ical
lymat eri
ali
zedview
def i
nit
ionsal soper manent lystoredindat abasesamel ikeav iew definition.InOr acl
e,ifwewantt o
viewmat erializedv i
ewdef ini
tionsthenwear eusing“user_mv i
ews”dat adi cti
onar y
.
MUARLISI R 2015
78

Cl
assi
fi
cat
ion:
Publ
ic
SQL>descuser _mv i
ews;
SQL>sel ectquer yfrom user_mv i
ewswher emv iew_name=‟ MV1‟;
SQL>sel ectrowi d,sno,snamef rom base;
SQL>sel ectrowi d,sno,namef rom v1;
Here,v i
ew rowi d‟sareal sosameasbaset ablerowi d‟sthat‟
swhyv i
ew doesnotst oredat a.That‟s
whyv i
ewi sal socal l
edas“ Virt
ualtable”or“ Wi ndowofat able”
.Throught hev i
ewonl ywecanv iew(or)
wecanaccessbaset abledata.Gener al
ly,viewst oresst or
edquer yinmemor y
.
SQL>sel ectrowi d,sno,namef rom mv 1;
Here,mat eri
alizedv i
ewr owid‟sar ediff
er entfrom „ Baset abl
e‟rowid‟saredi f
ferentfr
om „Baset able‟
rowid‟sthat‟swhymat er
ial
izedview‟sst oresdat a.
SQL>updat ebasedsetname=upper (name) ;
SQL>sel ect*f rom base;
SQL>sel ect*f rom v1;
SQL>sel ect*f rom mv 1;
Materiali
zedv iew alsost or
esdat asamel i
keat ablebut ,whenwear erefreshingmat er
ial
izedv i
ew it
synchronizesdat abasedon“ Basetables” .InOr acle,ifwewantt orefr
eshmat eri
ali
zedv i
ewt henwe
areusing“ Refresh”procedur efr
om “dbms_ mv iew”package.
Syntax:
SQL>execdbms_ mv i
ew.ref
resh(„materiali
zedv i
ewname‟ );
Dbms_ mv iew: predefi
nedpackagei nPL/ SQLRef r
esh( „
M. Vname‟ ):
Predefinedprocedur ename.
SQL>descdbms_ mv i
ew;
Eg:SQL>execdbms_ mv i
ew. r
efr
esh(„mv 1‟ )
;
SQL>sel ect*f rom mv 1;

ExecutivePr ocess:
InOr acle,whenev erwear er equest i
ngi nformationf rom thev i
ew using„ SELECT‟st atement ,then
Oracleser verdi rectlyexecut esv iew definit
ionsfrom t he„Dat aDi cti
onary‟
.That‟swhyv iew doesnot
i
mpr ovesper f
or mance.
Whenv er,wear ecr eat i
ngamat eri
alizedv i
ewt henOr acleserveraut omaticall
ystoresmat eri
ali
zedv iew
defi
niti
onsi na“ Dat aDict i
onary ”andal soresultoft hequeryisst oredindiff
erentplacewi t
hindatabase.
Whenev eruserr equest i
ngmat eri
ali
zedv i
ew thesel ectstatementt henOr acl
eser verdir
ectlyretri
ev e
dataf r
om mat eriali
zedv iew whenev erwear er efreshingmat eriali
zedv i
ew thenonl yor acleser ver
executesmat erializedv i
ewdef i
niti
onsbasedont hesedef ini
tions“ Basetables”areef f
ectedthenonl y
Oracleser versy nchr onize“ Baset able”dat aintomat eri
ali
zedv iew.Int hisprocessi fwear enot
ref
reshingmat erializedv iewt hen“ Baset able”arenev ereffected.Thisprocessaut omat i
call
yimpr oves
perf
or manceoft hequer yt hat‟swhymat eri
ali
zedv iewimpr ovesper formance.
Oracle,hav i
ngt wot ypesofmat eri
ali
zedv iews:
Compl eterefr eshmat eri
alizedv i
ews
Fastr efreshmat eri
ali
zedv i
ews
MUARLISI R 2015
79

Cl
assi
fi
cat
ion:
Publ
ic
1.COMPLETEREFRESHMATERI ALIZEDVI EW:
In Or acle,bydef aul tmat eriali
zed viewsar ecompleterefresh materi
ali
zed views.Theset ypeof
mat erial
izedv iewsdoesnotgi vemor eperformancewhenwear erefr
eshingmat eri
ali
zedv i
ewsnumber
oftimesbecausei nt hesemat eri
ali
zedv i
ewswhenev erwear erefr
esheingmateriali
zedv i
ewsint
ernal
l
y
rowi d‟sar er ecr eated.I fwear enotmodi fyi
ngdatainbaset abl
ealsot oovercomet hi
sproblem t
o
i
mpr ovemor eper formanceofquer ythenor acl
eint
roduced“Fastrefr
eshmat er
iali
zedv i
ews”.
Synt ax:
Creat emat eri
al i
zedv i
ewv iewname
ref
r eshcompl ete
as
selectst atement ;
Eg: SQL>sel ectr owi d,sno, namef rom mv 1;SQL>
execdbms_ mv iew.ref r
esh(„mv 1‟);SQL>select
rowi d,sno, namef r
om mv 1; [
hererowi d‟
sar e
changed]

Dat
e:28/
4/15

2.FASTREFRESHMATERI ALIZEDVI EW:


Theset ypeofmat er
iali
zedv i
ewsar ealsocal
l
edasI ncr
ementalref
reshmat eri
ali
zedviews.These
mat erial
i
zedv i
ewsper f
ormanceisv eryhi
ghcomparetocompl
eterefr
eshmat eri
ali
zedvi
ewsbecause
i
nt hesemat eri
ali
zedv i
ewsr owidsar enev
erchangedwhenwear er ef
reshi
ngmat er
iali
zedviews
numberoft i
mesal so.
Synt ax:
creat emateri
ali
zedv i
ewv iewname
refreshfast
as
selectstatement;

Beforewear eusing“ FastRef


reshmateri
ali
zedvi
ews”t henwemustcapt urechangesmadein“Basetable”
forthi
spur poseor acleprovi
dedamechani sm cal
l
ed“ Mat
erial
i
zedv i
ew Log”i.e.
,whenwear ecreating
“Material
izedv i
ew Log”or acl
eservercaptur
ethechangesf rom basetablesandst ori
ngi
ntoappr
opr i
ate
datadi cti
onari
es.That ‟swhybef or
ewear eusi
ngf astref
reshmat er
ial
izedviewst henwemustcr eate
materiali
zedv i
ewl ogon
“Baset able”.
Syntax:
Createmat eri
ali
zedv iewlogonbasetablename;
Eg:
SQL>sel ect*from base;
SNO NAME
--
--
--
---
----
--
1 A
MUARLISI R 2015
80

Cl
assi
fi
cat
ion:
Publ
ic
B
C
D
SQL>cr eatemat er
iali
zedv i
ewl ogonbase;
SQL>cr eatemat er
iali
zedv i
ewmk1;
ref
r eshfast
as
select*from base;
SQL>sel ectrowid,
sno,namef rom mk1;
SQL>updat ebasesetname=‟ xy ‟wher
esno=1;
SQL>execdbms_ mv i
ew.ref
resh(„mk1‟
);
SQL>sel ectrowid,sno,namef rom mk1;
[Her er
owid‟sarenotchangedonl ydat
aisaff
ect
ed]

Ondemand/Oncommi t:
I
nOracl
e,wecanref
reshmat
eri
ali
zedv
iewsi
n2way
s.
Manuall
y
Automati
cal
l
y

Manuall
y:In manual ,met hod we ar er efreshi
ng mater
ial
ized view usi
ng
“dbms_mview”package.Thi smethodisalsocalledas“
OnDemand”met hod.Bydefaul
tmethodis
“Ondemand” .
Automati
cally:Wecanal soref
reshmat er
ial
izedv i
ewwit
houtusing“dbms_mv i
ew”package.Thi
s
methodisalsocalledas“ OnCommi t
”met hod.
Synt ax:
creat emat
eri
alizedviewviewname
refreshcomplete/ref
reshfastondemand/ oncommi tas
selectstat
ement ;

Eg:
SQL>createmat eri
ali
zedvi
ewmk2
ref
reshfastoncommi t
as
sel
ect*from base;
SQL>select*from mk2;
SNO NAME
---
--
--
--
--
--
---
--
--
--
--
--
-
1 xy
2 B
3 C
4 D
SQL>updat ebasesetname=‟zz‟wher
esno=2;
SQL>select*from base;
MUARLISIR 201
5
81

Cl
assi
fi
cat
ion:
Publ
ic
SNO NAME
-
--
--
--
--
--
--
--
--
--
--
--
--
--
1 xy
2 zz
3 C
4 D

SQL>select*from mk2;
SNO NAME
--
--
--
--
--
---
--
--
--
---
--
--
-
1 xy
2 B
3 C
4 D

SQL>commi t;
SQL>select*from mk2;
SNO NAME
--
--
--
--
---
--
--
--
--
---
--
--
-
1 xy
2 zz
3 C
4 D

I
nall
databasesyst
ems,i
fwewantt
orest
ri
ctt
abl
ecol
umnsf
rom onuseri
ntoanot
herusert
henal
so
weareusi
ng“Views”.

DATACONTROLLANGUAGE( DCL):
Grant-
>givi
ngpermi
ssi
ons
Revoke->cancel
per
missi
ons

Creati
ngaUser :
SQL>connsy sassy sdba
EnterPassword:sy
s
OR
SQL>connsy stem/manager

Syntax:
Creat
euserusernamei dent
ifi
edbypassword;
Grantconnect
,resour
ce( or
)dbatousername;SQL>
connusername/password;

Processf
orcreat
ingaUser:
SQL>connsysassy sdba
MUARLISIR 2015
82

Cl
assi
fi
cat
ion:
Publ
ic
EnterPasswor d:sys
SQL>cr eateusermur aliidentifi
edbymur al
i
;
SQL>gr antconnect ,r
esour cet omur ali
;
SQL>connmur al
i/murali
;
SQL>sel ect*from emp;
Err
or:tabl e(or)viewdoesnotexi st
s;
SQL>connscot t/ti
ger;
SQL>gr antallonempt omur ali
;
SQL>connmur al
i/murali
;
SQL>sel ect*from emp;
Err
or:tabl e(or)viewdoesnotexi st
s.
SQL>sel ect*from scott.emp;
SQL>cr eatesynony m abf orscot t.
emp;
SQL>sel ect*from ab;
Pri
v i
l
ege:Pr i
vi
legei sarightorper missi
onwhichisusedt ogiv
ent
otheanot
her“
user
”.
All
dat abasesy st
emshav ingt wot ypesofpri
vi
leges.Theyare:
Syst em Privil
ege
Obj ectPrivi
lege

ThesePr
ivi
l
egesar
eusedt
opr
ovi
desecur
it
yfordat
abaseobj
ect
s.

Dat
e:29/
4/15

1.System Privi
leges:
System Pri
v i
l
egesar egi venbydat abaseadmi ni
str
ator.Thesepr
ivi
legesar
ecreat
etable,cr
eat
eany
vi
ew, cr
eateanymat eri
ali
zedvi
ew, createsession,creat
eprocedur
e,creat
eanyi
ndex,
….;
Oraclehavingmor ethan80sy stem pr i
v i
l
eges.Thesepr iv
il
egesareusedtousersall
owedtocreat
e
databaseobject,audit
ordatabaseobj ects.
Syntax:
grantsyst
em pr i
vil
egestousername1, username2,……;

Eg:SQL>connsysassysdba
Ent
erpassword:
sys
SQL>grantcr
eat
eprocedure,
creat
eanymat
eri
ali
zedv
iew,
creat
eanyi
ndext
oscot
t,mur
ali
;

ROLES
Roleisnothingbutsetofsyst
em privil
egesorsetofobjectpr
ivi
l
ege.Userdefi
nedrowsar
ecr eatedby
databaseadmi nist
rator
.Inamultiuserenvi
ronment,numberofuser sworksonsameproject.I
nt his
case,somet imenumberofuser sr equi
rescommonsetofpr i
vi
leges.I
nt hi
scaseonlydat abase
administ
ratorcreati
ngauserdefi
nedr ol
eandthenassignssetofpri
vil
egesint
orol
eandthenonlyt hat
rol
egiventot henumberofusers.

MUARLISI
R 2015
83

Cl
assi
fi
cat
ion:
Publ
ic
Cr
eat
ingUserDefinedRole:
St
ep1:Createarole
St
ep2:Assignsystem pr
ivi
l
egest
orole
St
ep3:Assignrol
enamet onumberofuser
s.

STEP1:Cr eateaRol e:
Syntax:creater oler olename;
STEP2:Assi gnSy stem priv
il
egest oRol e
Syntax:grantsy stem pr i
vil
egetor olename;
STEP3:Assi gnRol enamet onumberofuser s.
Syntax:grantr olenamet ousername1, username2,….;
Eg:
SQL>connsy sassy sdba
Enterpasswor d: sy s
SQL>cr eaterol er 1;
Rolecreated
SQL>gr antcr eat eanymat eri
ali
zedv iew,createtri
gger,
creat
eprocedur
etor
1;SQL>gr
ant
r1toscot t
, mur ali,dinesh;
I
nOr acle,ifwewantt oviewallthesy stem pri
vil
egesrel
atedtorol
ethenweareusi
ng“
rol
e_sy
s_pr
ivs”
datadicti
onar y.
Eg:SQL>descr ole_sys_pri
vs;
SQL>sel ectrol e,pr i
vil
egef r
om role_ sys_pri
vswher erol
e=‟R1‟;
ROLE PRIVILEGE
--
--
--
---
--
--
---
---
--
------
-----
--
--
--
---
--
--
--
---
---
--
-----
-
R1 CREATETRI GGER
R1 CREATEANYMATERI ALIZEDVIEW
R1 CREATEPROCEDURE

Pr
edefi
nedRol es:
Wheneverwear ei
nst
all
i
ngor acl
eserv
erthenaut
omat
ical
l
y„3‟pr
edef
inedr
olesar
ecr
eat
ed.Theyar
e:
Connect->enduserpurpose
Resource->devel
operpurpose
DBA- >databaseadmini
strat
orpur
pose

Eg:SQL>descr ol
e_sys_pr
ivs;
SQL>selectr
ole,pri
vi
legefrom r
ole_
sys_
pri
vswher
erol
ein(
„connect
‟,
‟r
esour
ce‟
);

MUARLISI
R 2015
84

Cl
assi
fi
cat
ion:
Publ
ic
NOTE:InOracl
e,“connectr
ole”i
nter
nal
lyhaving“cr
eat
esession”syst
em pri
vi
lege.Thi
sprivi
l
egeis
usedtousersall
owedtoconnecttothe“OracleSer
ver
”.SQL>selectr
ole,
pri
vil
egefrom r
ole_sy
s_pr
ivs
whererol
ein(„
DBA‟ )
;

2.Obj ectPr ivi


lege:
ObjectPr ivil
egesar egivenbyei therdatabasedev el
oper sordatabaseadmi ni
str
ator.Thesepr i
vil
eges
areusedt o“ Users”areall
owedt oper f
orm someoper ationsont heobject.Or
acl
ehav i
ngi nser
t,update,
delete,selectobj ectpri
vil
egesr elat
edt otable.These„ 4‟objectpri
vil
egesalsorepresentedbyusi ng
“al
l”key wor d.
Oracleal sosuppor t
sexecut eobjectpri
vil
egef orPL/SQLobj ectsandal sosupport
sr ead,wri
teobject
pri
v i
l
egesf or“utl_f
il
e”package.
Syntax:
grantobj ectprivil
egeonobj ect
namet ousernames/ r
olename/public;
Dat e:
30/4/ 15

SQL>connscot t
/ti
ger;
SQL>grantall
onempt omur ali
;
SQL>grantall
onempt or1;
SQL>grantall
onempt opublic;
NOTE:InOracle,wecanal sogiveobj
ectpr
ivi
l
egestopart
icul
arcol
umns.Int
hiscasewemustspeci
fy
numberofcolumns.Inthi
scasewemustspeci fynumberofcol
umnswithi
nparent
hesi
s“(
)”.
Eg:SQL>grantupdate(
ename)onempt omurali
;

WI THGRANTOPTI ON:
Whor eceives“
WithGrantOpti
on”cl
auset
hoseuser
sallowedt
ogiv
esameobj ectpr
ivi
l
egest
oanot
her
users.
Syntax:
grantobjectpr
ivi
l
egesonobjectnametouser
names/publ
icwi
thgr
antopt
ion;

Eg:SQL>gr antallonempt omurali


withgr antopti
on;
NOTE:Inall dat
abasesy st
ems“WithGr antOpt i
on”cl
ausedoesnotworkwithrol
es.
Eg:SQL>gr antallonempt or1wit
hgr antoption;
Err
or:cannotGRANTt oarolewit
hGRANTOPTI ON.
I
nOr acl
e,allobjectpr
ivi
l
egesarestoredunder“ user_
tab_
pri
vs”dat
adict
ionary
.Eg:SQL>
descuser_tab_pri
vs;

REVOKE:
Thiscommandi susedt o“CANCEL”system privi
l
eges,obj
ectpr
ivi
legesf
rom user
s.
Syntax:
Revokesystem pri
vi
legesf
rom user1,
user2,….;
Revokeobjectpri
vi
legesonobjectnamef rom user
name/publ
ic;

Eg:SQL>connsy
sassy
sdba;
MUARLISIR 2015
85

Cl
assi
fi
cat
ion:
Publ
ic
Enterpasswor d: sys
SQL>r evokecr eateanymat er
iali
zedviewfr
om scott;
Revoke
succeeded
Generall
y,ifwewantt or estr
icttabl
ecolumnsf rom oneuserint
oanotheruserthenwear
ecr
eat
ing
vi
ewswi t
hr equiredcolumnsandt henonlyt
hatviewgiventothenumberofusers.
Syntax:grantallonv i
ewnamet ouser1,
user
2,….
;
SQL>connscot t
/ t
iger
SQL>cr eateorr eplacev i
ewv v1
as
sel
ectempno, ename, sal
,deptnof r
om emp;
SQL>sel ect*from v 1;
SQL>gr antallonv 1tomur ali
;
SQL>connmur ali/murali
;
SQL>sel ect*from scot t.
v1;

ForceVi ew( or)ForcedVi ew:


InOr acle,wecanal socreateviewswit
houtusingbaset
abl
es.Theset
ypeofv
iewsar
eal
socal
l
edas
“For ceVi ews” .
Synt ax:
creat eorr eplaceforceviewv i
ewname
as
select*f rom wel come;
Eg: SQL>cr eateorreplaceforcevi
ewv 2
as
select*f rom wel come;
War ning:v iewcr eat
edwi thcompil
ati
onerror
s.
SQL>cr eat etabl
ewel come( snonumber(10)
);
SQL>al terv i
ewv 2compi le;
SQL>descv 2;

ReadOnl yv iews:
InOr acl
e,wecanal socreat
ereadonlyv i
ewsusing“wit
hreadonly”opti
oncl ause.I
nReadonl
yvi
ews
wecannotper f orm DMLoper at
ions.Thesevi
ewsareusedforrepor
tingpurpose.
Syntax:
Createorr eplacev iewv i
ewname
as
select*from t ablenamewher econditi
onwithreadonl
y;Eg:
SQL>cr eateorr epl
acev i
ewv 3as

sel
ect*from empwithr
eadonly;
SQL>deletefr
om v3wheredept
no=10;
Err
or:cannotdel
etef
rom vi
ew.
MUARLISIR 2015
86

Cl
assi
fi
cat
ion:
Publ
ic
Wi thCheckVi ew:
Ifwewantt opr ovideconstrai
nttypemechanism onv i
ewsthenwear eusi
ng“Wit
hCheckOpti
on”
clauseonv iews.Whenav i
ew contains“wi
thcheckopt
ion”cl
ause,t
henwearenotall
owedt
oinser
t
othert hanwher econdit
ionvaluesthroughvi
ew2basetable.
Sy ntax:
creat eorreplaceviewviewname
as
select*f rom tabl
enamewher econdi t
ionwit
hcheckopti
on;Eg:
SQL>cr eateorreplaceviewv4as

select*from empwher edeptno=10wi thcheckopt i


on;SQL>
select*from v4;
Testing:
SQL>i nser
tint
ov 4(empno,
ename, deptno)v
alues(1,
‟abc‟
,30);Er
ror
:vi
ew
withcheckoptionwher ecl
ausev i
olated.
SQL>i nserti
ntov 4(empno,ename,deptno)values(
1.‟abc,‟
10);1Row
created
SQL>sel ect*from emp;
Wecanal sodropv iewusing“dropv iewvi
ewname” .

NOTE:I nalldatabasesystemsthroughtheviewswecanachi
evelogi
caldataindependencei .
e.,
logi
cal
dataindependencer ef
erswhenev erweareaddinganewenti
tyi
n“conceptuall
ev el
”itisnoteff
ectedin
exter
nal l
evel.i
.e.
,wheneverwear eaddinganewcolumninatabl
eiti
snev ereffectedinav i
ew
becauseofLogi calDataIndependence.Eg:
SQL>altert
abl
eempaddaddr essv archar2(10)
;SQL>
sel
ect*f r
om emp;

SQL>sel
ect*f
rom v
4;

Dat
e:1/
5/15

I
NDEXES:
Indexisandat abaseobj ectwhichisusedt oretr
ievedataveryfastfrom t
hedatabase.Thi
sprocess
automaticall
yimprovesper for
manceofquery .I
nalldat
abasesy st
emscr eat
ingI
ndexesin2ways:
Automat i
call
y
Manual l
y
1.Automat ical
ly:
Whenev erwear ecreati
ng“ Pri
maryKey”or“UniqueKey”thenonlydatabaseserv
ersautomati
cal
l
y
creat
esb- tr
eeindexesont hosecolumns.
2.Manual ly
:
Wecanal socreate“I
ndexes”expli
cit
lybyusing“cr
eateindex”command.
MUARLISI
R 2015
87

Cl
assi
fi
cat
ion:
Publ
ic
InOracle,wear ecr
eati
ngindexexpli
cit
lybyusingfol
l
owingsyntax:
Syntax:
Createindexindexnameont abl
ename( col
umnname);
Generall
y,indexesarecr
eatedon“tablecolumns”andal
soindexesarecr
eat
edby“
dat
abase
administr
ator”only
.

InOr acl e,whenev erwear er equest i


ngdat ausi ng“ where”clauseor“ Or derby ”clausethenonl yoracleserver
sear chingf or“Indexes”i nappr opriate“ DataDi cti
onary”wi t
hinOr acledat abase.I f“where”clausecol umns
or“ Or derby ”clausecol umnshav ingi ndext henOr acleser veruses“ I
ndexScan”met hodforr etr
ievi
ngdat a
from dat abase.Thi sprocessaut omat i
call
yimpr ovesper f
ormanceoft hequer y.
NOTE:I nOr acle,whenev er“ where”cl ausecont ai
ns“ notequalt o”( !
=,<>) ,“ i
snull”,“i
snotnul l”operators
thenor acleser v erdoesnotsear chf orindexes.I ft
hosecol umnsal readyhav ingindexesalso.
Or aclehav i
ng2t y
pesofI ndexes:
B-treesI ndexes
BitMapI ndexes
B-Tr eeI ndexes:I nOr acle,bydef aul ti
ndexesar eb-treeindexes.Whenev erwear er equesti
ngdat ausi ng
“wher e”or“ Orderby ”col umns,al sot hosecol umnshav i
ngb- t
reei ndexest henOr acleserveraut omaticall
y
creat es“ b-treest ructure”basedoni ndexedcol umns.I nthis“b-treest ructure”alway s“Leafbl ocks”stores
act ualdat aal ongwi th“ Rowi d‟s”.Basedont he“ Wher e”clausecol umnsOr acleserverretr
ievesdat afrom
these“ Leafbl ocks”usi ng“ IndexScanMet hod”.Thisprocessv eryf ast
lyr etr
ievedat afrom database.

Sy
ntax:
DEVELOPERs Dat
aBaseAdmi
nist
rat
ors
SQL>sel
ect*f
rom empwher
eename=‟
KING‟
; SQL>cr
eat
eindexi
n1onemp(
ename)
;

SQL>createindexin1onemp( ename);
I
nOr acl
e,al
lindexesi nf
ormati
onst or
edunder“user_i
ndexes”datadict
ionar
y.
Eg:SQL>descuser _indexes;
SQL>selecti
ndex_ name, i
ndex_typefr
om user
_indexeswheretable_
name=‟ EMP‟
;
Output:
I
NDEX_ NAME I
NDEX_ TYPE
-
---
--
--
--
--
--
--
--
--
---
--
--
--
---
---
--
--
--
--
-
MUARLISIR 2015
88

Cl
assi
fi
cat
ion:
Publ
ic
PK_
EMP NORMAL
I
N1 NORMAL

NOTE:In Or
acl
e,ifyou wanttov i
ew col
umn names al
ong wi
thI
ndex names t
hen we ar
e usi
ng

user
_ind_
col
umns”dat
adict
ionar
y.

Eg:SQL>descuser_i
nd_
columns;
SQL>selecti
ndex_
name,column_
namef
rom user
_ind_
col
umnswher
etabl
e_name=‟
EMP‟
;

Output:
I
NDEX_ NAME COLUMN_
TYPE
-
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
PK_EMP EMPNO
I
N1 ENAME

NOTE:Inal
ldat
abasesy st
emsusingindexeswecanachi
eve“Physi
calDat
aIndependence”i
.e.,whenev
er
weareaddingindexes(
Int
ernalLev
el)itisnotef
fect
edintable(
Concept
ualLevel
)Butper formanceis
ef
fect
ed.

Dat
e:2/
5/15

I
nOr acle,ifyouwantt ov i
ew quer yperformancethendatabaseadmi
nist
ratorvi
ewingpl ant
abl
es.These
tabl
esar eautomaticall
ycr eatedby“ Oracleserver
”.Bef
orewear edi
spl
ayingplantabl
et henwemustuse
“EXPLAI N PLAN FOR”cl ausei nfrontoft hequeryandt henonl
ywecandi splayplantableusi
ngdispl
ay
functionf r
om “dbms_ xplan”package.
Step1:
Syntax:SQL>expl ai
npl anf orselectstat
ement ;
Step2: (displ
ayplantable)
SQL>sel ect*fr
om table(dbms_ xplan.
display)
;Eg:
(wit
houtusi ngIndexes)
SQL>sel ect*fr
om empwher eename=‟ KING‟;

Test
ingPerf
ormance
SQL>expl
ainpl
anforsel
ect*fr
om empwhereename=‟
KING‟
;
SQL>sel
ect*fr
om tabl
e(dbms_
xpl
an.di
spl
ay(
));

Wit
hUsingI ndexes:
SQL>cr
eateindexin1onemp(ename)
;
SQL>select*from empwher
eename=‟KI
NG‟
;

Test
ingPerfor
mance
SQL>explai
nplanforselect*f
rom empwher eename=‟
KING‟
;
SQL>slel
ect*from t
able(dbms_xpl
an.
displ
ay()
);

MUARLISI
R 2015
89

Cl
assi
fi
cat
ion:
Publ
ic
FunctionBasedI ndexes:
Oracle8i i
ntr
oduced“ Functi
onBasedI ndexes”bydef ault“funct
ionbasedindexes”areb-tr
eei ndexes.
Generall
y ,wheneverwear erequesti
ngdat ausingf unctions(or)expressi
onst henoracl
eser verdoesnot
searchf orIndexesifthosecol umnsal readyhav i
ng“ I
ndexes”al so.Toov ercomet hi
spr oblem Or acle8i
i
ntroducedext ensi
onoft heb- t
reeindexescall
ed“ FunctionBasedI ndexes”whichisusedt ocr eateIndexes
oncol umnsal ongwithf uncti
ons(or)expressions.Thenonl yOracl
eserversearchi
ngf orindexesi fwear e
requesti
ngdat ausingfunctions(or
)expressionsalso.

Synt
ax:
cr
eatei
ndexi
ndexnameont
abl
ename(
funct
ionname(
col
umnname)orexpr
essi
on)
;

Wit
houtusi
ngfuncti
onsbasedIndexes:
SQL>sel
ect*f
rom empwher eupper(
ename)
=‟KI
NG‟
;

Test
ingPer for
mance
SQL>explai
nplanforselect*fr
om empwher
eupper(
ename)=‟
KING‟;
SQL>select*
fr
om tabl
e(dbms_x
plan.displ
ay(
));
[her
eor
acl
eser
verdoesnotsear
chfori
ndexes]

Wit
husingf uncti
onbasedIndexes:
SQL>createindexin2onemp(upper(
ename))
;
SQL>select*from empwhereupper(ename)
=‟KI
NG‟
;

Test
ingPerf
ormance
SQL>expl
ainpl
anforsel
ect*fr
om whereupper(
ename)
=‟KI
NG‟
;
SQL>sel
ect*fr
om tabl
e(dbms_
xpl
an.di
spl
ay())
;

SQL>descuser _
indexes;
SQL>selecti
ndex_name,index_t
ypefr
om user
_indexeswher
etabl
e_name=‟
EMP‟
;
I
NDEX_ NAME I
NDEX_TYPE
-
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
I
N2 FUNCTI
ONBASEDNORMAL

VIRTUALCOLUMNS
Oracle11gintroduced“ Vir
tualColumns”i nat abl
ewhi chstores“St
oredExpr essi
on”directl
yinOracle
databasepri
or( meanbef ore)to11gDat abaseAdmi ni
strat
orsonl
ystores“Stor
edExpr essions”i
ndi
rect
ly
using“VIEWS”,“ Funct
ionBasedI ndexes”.Whereaswhenwear eusing“Vir
tualColumns”wecanst ore
“Stor
edExpressions”di
rectl
yindatabaseusing“Generat
edAl way
sAs”clause.

Synt
ax:
col
umnname dat
aty
pe(
size)gener
atedal
way
sas(
stor
edexpr
essi
on)
[vi
rt
ual
]
MUARLISI
R 2015
90

Cl
assi
fi
cat
ion:
Publ
ic
Eg:
SQL>createtablet
est(
anumber(10),
bnumber
(10)
,cnumber
(10)gener
atedal
way
sas(
a+b)v
irt
ual
);
SQL>i
nser ti
ntotest
(a,
b)val
ues(
20,40);
SQL>select*from t
est;

A B C
--
--
--
--
--
---
---
-
20 40 60
I
fwewantt ov i
ew“ Vir
tualColumn”expressi
ont henweareusi
ng“dat
a_defaul
t”pr
opertyf
rom
“user
_tab_columns”dat adict
ionary.
SQL>descuser _t
ab_columns;
SQL>sel ectcolumn_name, data_def
aul
tfrom user_t
ab_
columnswheretabl
e_name=‟TEST‟;
COLUMN_ NAME DATA_ DEFAULT
--
--
--
--
--
---
---
--
--
--
--
---
--
--
--
--
--
---
--
--
--
---
C A+B

Or
acl
ehavi
ngtwotypesofb-t
reei
ndexes.
Nonuni
queb-t
reeIndexes
Uni
queb-t
reeI
ndexes

Bydefault
,al
laut
omaticIndexesare“Uni
queb- t
reeIndexes”andalsoal
lexpli
citI
ndexesare“Nonuni
queb-
tr
eeIndexes”
.Bydefault
,“Uniqueb-t
reeIndexes”perfor
mancei sveryhighcompar eto“Nonuni
queb-t
ree
I
ndexes”.Wecanalsocreate“Uni
queb-tr
eeIndexes”expli
cit
lybyusingfoll
owi
ngsy ntax.

Syntax:
Createuniqueindexindexnameont abl
ename(columnname) ;
Eg:SQL>cr eateuniqueindexin3onemp( ename);
Indexcreated
NOTE:Wear enotal l
owedt ocreateuni
queindexesonduplicatev
aluecol
umns.SQL>
createuniqueindexin4onemp( j
ob);
ERROR: cannotCREATEUNI QUEI NDEX:dupli
catekeyfound.

2.BITMAPI NDEX:
Oracle7.3,i
ntr
oducedBitMapI ndexes.BitMapIndexesareusedinDat
aWar
ehousi
ngappl
i
cat
ions.
Generall
y,Bi
tMapI ndexesarecreatedon“ LowCardi
nali
tyColumns”
.
Syntax:
createbi
tmapi ndexindexnameont ablename(col
umnname) ;

Dat
e:4/
5/15

MUARLISI
R 2015
91

Cl
assi
fi
cat
ion:
Publ
ic
Eg1: Cardinal
it
yofempno=14/ 14=1( highcardi
nali
ty)->b-
tree
Eg2: Cardinal
it
yofjob=5/ 14=0.367….( lowcardinal
ity)-
>bitmapi ndexes
Whenev erwear ecreati
nga“ BitMapI ndex”thenor acl
eser verautomat i
cal
lycreatesa“ Bi
tMapTabl e”
basedthecol umnv aluesinat
abl e.Whenev eruserrequesti
ngdat ausing“Wher e”clauset
henor acleser
v er
automaticall
yuses“ I
ndexScan”i nter
nallyon“BitMapTabl e”al soperform operat
ionson“ Bi
ts”wi t
hin“Bit
MapTabl e”.Whenwear eusingl ogicaloperatorsin“ Where”clauset henor acleserveraut omati
cally
convert
st heresult
antBitMapinto“ ROWI D”usi
nga“ Inter
nalBitMap”f unct
ion.

SQL>cr eatebit
mapi ndexabconemp( job)
;
SQL>descuser _
indexes;
SQL>sel ecti
ndex_type,index_namefrom user
_indexeswher
etabl
e_name=‟
EMP‟
;
Output:
I
NDEX_ TYPE INDEX_ NAME
-
---
---
--
--
---
--
--
--
--
--
--
--
--
---
--
---
-
NORMAL PK_ EMP
BITMAP ABC
I
nOr acle,wecanal sodropI ndexusi
ng
“dropindexindexname” ;

SYNONYMS

Synonymsi sadat abaseobj ectwhi chhi


desanot herschemausername,obj ectname.
Synonymsalsopr ovidessecurit
yf ort
heori
ginalobject.I
tisan“Ali
asname”or“Reference
Name”f ort
heoriginalobject
s.Sy nonymsarecreatedbydat abaseadmini
str
ator
s.
Al
l dat
abasesystemshav i
ng2t ypesofsynonyms
Publi
cSynonyms
Pri
vateSynony ms

I
nalldat
abasesy
stemsbydef
aul
tSy
nony
msar
e“PRI
VATESy
nony
ms”
.
Synt
ax:
MUARLISI
R 2015
92

Cl
assi
fi
cat
ion:
Publ
ic
createsy
nonym synony
mnamefor
username.Obj
ectname@dat
abasel
ink;

InOracle,
ifyouwantt ocreat
ePublicSynonymst henweareusi
ng“CREATEPUBLI CSYNONYM”pri
vil
eget
o
userotherwiseoracleser
verret
urnsas“Insuf
fi
cientPr
ivi
l
egeErr
or”
.Syntax:gr
antcreat
epubl
i
csynonymto
username;
Syntax:
createpubli
csy nonym sy
nonymnamef or
username.Obj ectname@databaseli
nk;

Scot
t/t
iger SQL>connmur ali
/murali SQL>conna1/a1
SQL>grantal
lonemp SQL>sel ect*f rom scott.
emp; SQL>sel
ect*f
rom scot
t.
emp;
tomurali
,a1; SQL>cr eatesynony m abcf orscot
t.
emp SQL>sel
ect*f
rom abc;
SQL>sel ect*f rom abc;
SQL>cr eatepubl icsy nonym xy
scott.
emp;
Err
or :
Insuffi
cientPr i
vil
ege
SQL>connsy sassy sdba;
Enterpasswor d: sys
SQL>gr antcr eatepubl i
csy nonym
mur al
i;
SQL>connmur al
i/murali
;
SQL>cr eatepubl icsy nonym xy
scott.
emp;
SQL>sel ect*f rom xy; SQL>sel
ect*f
rom xy
;

Al
lSynony msi
nfor
mat i
onstor
edunder“user
_sy
nony
ms”dat
adi
cti
onar
y.
SQL>descuser_synonyms;
Wecanal sodr
opsy nonymsbyusi
ng
“dr
opsy nonym sy
nony mname”

LOCKS

Locki
ngisamechanism whi
chpr
event
sunaut
hor
izedaccessf
orourr
esour
ce.Whol
edat
abasesy
stems
havi
ng2typesoflocks.
RowLevelLocks.
Tabl
eLevelLocks

RowLevelLocks:Oracle6.0introduced“ RowLev elLocks”.I


fyouwantt oestabl
i
shes“RowLevelLocks”
t
henwear eusing“f orupdate”cl auseinalldatabases.Thisclauseusedonl yin“
Select
”stat
ement.In
t
hismethodwear elockingsetofr ows.
Synt
ax:sel
ect*fr
om tablenamewher econdi ti
onforupdate[nowait]
;
Wheneverweareperfor
mi nglockst henanot heruserquerythedataquer ybutt
heycannotperf
orm DML
oper
ati
onwheneverwear eusing“Commi t
”and“ Roll
back”locksarereleased.

MUARLISI
R 2015
93

Cl
assi
fi
cat
ion:
Publ
ic
Dat
e:5/
5/15

Scot
t/t
iger Mur
ali
/mur
ali
SQL>select*f
rom empwher
edept
no=10 SQL> updat
e scott
.emp setsal=sal
+100
f
orupdate; wher
edeptno=10;
[
wecannotperfor
m DMLoperat
ions]
SQL>commi t;
[f
orreleasinglock]
NOWAI T:“Nowai t
”isanopt ionalcl
auseusedalongwith“f
orupdate”clause.Whenweareusi
ng“
nowai
t”
clauseoracleserv
eraut omat i
cal
lyret
urnscont
roltothecur
rentsessionif
anotherusernotreleasinglocksalso.I
nthi
scaseor acl
eserverr
eturnsaner r
or.ORA-
0054:
resourcebusy

Scot
t/t
iger Mur al
i/
mural
i
SQL>sel
ect*from scott
.empwher
e
dept
no=10forupdate;
SQL>select*fr
om empwher
edept
no=10
f
orupdatenowai t
;
ORA-0054:resour
cebusy
SQL>_

DEFAULTLOCKS:I nall
databasesystemswhenev erwear eusi
ngDMLoper at
ionsthen
automaticall
ydatabaseserversinter
nal
lyuses“ExclusiveLocks”.Thesear ealsocal
ledas“ Defaul
tLocks”
.
Eg:
Scot
t/ti
ger Mur al
i/
murali
SQL>updat eempsetsal =sal+100where
deptno=10; SQL>updat escott.empsetsal=sal+100
rowsupdat ed wheredeptno=10;
SQL>commi t;
[f
orreleasi
nglocks] [
wecoul dnotper form DMLoper at
ions
becauseof“ DefaultLocks”
]

DEADLOCKS:
Whenwet rytoper
form sameDMLoper at
ionsonsamer esourceatati
methroughdi
fferent
sessi
onsfora“si
ngleuser”ort
hroughdi
ff
erentuser
sthenor acl
eserv
eraut
omat i
cal
l
yr etur
ns
anerror
.
ORA-0060:deadl
ockdetected

Scott/t
iger Scot
t/t
iger
SQL>updateempsetsal=sal+100wher
e SQL>updateempsetsal=sal+100
dept
no=100; wheredepnto=20;
3rowsupdated rowsupdated
SQL>updateempsetsal =sal
+100
wheredept
no=20;
ORA-0060:
deadlockdetected
SQL>commi t
;[f
orrel
easinglocks]

201
MUARLISI
R 5
94

Cl
assi
fi
cat
ion:
Publ
ic
TABLELEVELLOCKS:
I
nt hi
smet hodwear elocki
ngatabl
e.Or
acl
ehav
ing2t
ypesoft
abl
elev
ell
ocks.“
Tabl
eLev
elLocks”ar
e
handledbyDat abaseAdmini
str
ator
s.
Sharelock
Exclusi
velock

1.Shar elock:Whenwear eusingthisl


ockanot
heruserquerythedatabutt heycannotper
for
m DML
oper at
ionsandal soatat imenumberofuserscanlocktheresource.
Syntax:lockt ablet
ablenamei nsharemode;
Here,alsowhenev erwear eusing“Commit”or“
Roll
back”thenonlyaut omati
call
ylocksar
erel
eased.
Eg:
Scott
/ti
ger Mur ali
/mural
i
SQL>l ockt ableempi nsharemode; SQL>select*from scott.
emp;
SQL>locktablescott.
empi nsharemode;
SQL>updat escott
.empsetsal =sal
+100;
[wecannotperfor
m DMLoper ati
ons]
SQL>commi t;[f
orrel
easinglock]

Exclusi
velock:Whenwear eusing“excl
usi
velocks”t
henanotheruserquerythedatabut
theycannotperf
orm DMLoper at
ionsandalsoatati
meonl yoneuserlocktheresour
ce.Sy
ntax:l
ock
tabl
et abl
enameinexclusi
v emode;
Eg:
Scott/t
iger Mural
i/
muar l
i
SQL>l ocktabl
eempi nexclusivemode; SQL>select*fr
om scott.
emp;
SQL>locktabl
escott.
empi nsharemode;
SQL>commi t;
[
forr
eleasi
ngl ocks]

NOTE:inalldatabasesyst
emswheneverweareusi
ngcur
sorl
ocki
ngmechani
sm t
henaut
omat
ical
l
y
dat
abaseser
versinter
nal
l
yuses“
Excl
usi
vemode”
.

SEQUENCE

Sequencei sandat abaseobjectwhichisusedt ogener at


e“ Sequencenumber s”automati
cal
ly
.General
ly
,
sequencesar eusedt ogenerates“Pri
marykeyv al
ues”aut omaticall
y.Gener
all
y,sequencesar
ecreat
edby
databaseadmi ni
str
ator.Sequenceisan“Independentdatabaseobj ect”
.Onceasequencehasbeencreated
thennumberofuser ssimultaneousl
yacceptsthat“sequence”.
Syntax:
createsequencesequencename
startwit
hn
i
ncrementbyn
minv al
uen
maxv al
uen

MUARLISI
R 2015
95

Cl
assi
fi
cat
ion:
Publ
ic
cycl
e/nocycle
cache/nocache;

I
nOracl
e,ifwewantt
oaccesssequencev
aluest
henwear
eusi
ng2pseudocol
umns.
Curr
val
Nextval

Syntax(currv
al)
:sequencename.cur rval;
Syntax(nextval
):sequencename.nextv al;
ThesePseudocol umnsar eusedinI nser t
,Update,Delet
e,Sel
ectst
atements.
I
nOr acle,i
fwewantt ogeneratesequencev aluesusing“SELECTstatement”t
henwemustuse“
dual
”tabl
e.
Syntax:sel
ectsequencename.currvalfrom dual;
Syntax:sel
ectsequencename.nextval from dual;

“Curr
v alpseudo”columnreturnscurrentvalueoft hesequenceifsequencesessionalreadyhavi
ngav al
ue.
Whereasnext val
pseudocolumnr eturnsnex tvaluesf
orsequenceupdate.
InOracle,ifwewantt ogeneratefi
rstsequencenumbert henwemustusenext valpseudocol umn.Because
curr
val pseudocolumnreturnsvalueifsequencesessi onalr
eadyhavingaval
ue.
Inal
ldat abasesystems,wear eusing“Currv
al ”pseudocolumnafterusi
ng“Nextval”pseudocolumnsonly.
Eg:SQL>cr eat
esequences1
star
twi th5
i
ncrementby2
maxv alue100;

Sequencecreated
SQL>selects1currval
from dual
;
Err
or:sequences1.cur
rval
isnotyetdef
inedi
nthi
ssessi
onSQL>
sel
ects1.nextv
alfr
om dual;5

SQL>sel
ects1.
next
valfr
om dual
;
7
SQL>sel
ects1.
next
valfr
om dual
;
9
SQL>sel
ects1.
next
valfr
om dual
;
11
SQL>sel
ects1.
cur
rval
from dual
;
11

MUARLISI
R 2015
96

Cl
assi
fi
cat
ion:
Publ
ic
Dat
e:6/
5/15

NOTE:I nsequencewecanal sochange“ Sequencepar ameterval


ues”byusing“ALTER”command.
Syntax:
al
tersequencesequencenamepar amet ernamenewv alue;Eg:
al
tersequences1i ncr
ementby- 1;
Sequenceal t
ered
I
nall dat
abasesy st
emswecanmodi f
yall sequenceparameterval
uesexcept“Star
twit
h”cl
ause.
Eg:SQL>al t
ersequences1st ar
twith3;
Err
or:cannotalt
erstart
ingsequencenumber

NOTE:Gener al
ly,
star
twit
hvaluescannotbel
esst
han“
minv
alue”
Eg: SQL>cr eat
esequences1
startwi t
h4
i
ncr ementby1
minv alue5
maxv alue100;
Error:STARTWI THcannotbelessthanMINVALUE

CACHE:Cachei san“ Optional ”cl ausedef i


nedi n“ Sequence”obj ectwhi chisusedt oaccess“ Sequence
values”v eryf ast
ly.Thi spr ocessaut omat icallyimpr ovesper f
ormanceoft heappl icati
on.Gener all
y,cachei s
anmemor yar eawhi chi susedt ost oresetof“ SequenceNumber s”
.
Gener all
y,whenev erwear ecr eat inga“ Sequence”t hosesequencesar ecr eatedi nhar ddisk.Whenev erwe
arer equest i
ngsequencesusi ngacl ientt ool, thenser verpr ocesschecksr equest edsequencei sav ai
lablein
cachememor yarea.I fitisnotav ailablet hencont rolgoest ohar ddiskandr eturns“Sequencev alue”f r
om
thedi skandst ori
ngi nto“ Cachememor yar ea”.Thenonl ythatv al
uer et
urnt ocl ienttool.Thi sdef aul
t
processr et ri
eves“SequenceVal ues”sl owl yfrom t hedat abasebecauseeachandev eryt i
meser verpr ocess
i
nt er acti
ngwi thdi sk.Toov ercomet hispr oblem t oaccesssequencev al
uesv er
yf astl
yt hendat abase
admi nistr
at ordefi
nes“ Cachepar amet er”i nsequenceobj ect.Basedont hepar amet erv al
uecachememor y
pre- all
ocat essetof“ Sequencenumber s” .Whenev erwear er equestingsequencest henser verpr ocess,
direct l
yaccesssequencev aluesf rom t he“ Cachememor y
”ar enotf r
om t he“ Harddi sk”.Thispr ocess
aut omat i
callyimprov esper formanceoft heappl i
cati
onbecauset hi
spr ocessr educesDi skI /
O(input/output)
.
Whenev ersy stem cr ashes( or )powerf ailur et henaut omat icall
ycachev al
uesar elost.
InOr acle,cachedef aultv al
uei s“20”andal socachemi nvaluei s“2”.
Eg: SQL>cr eatesequences1
star twi t
h1
cache1;
Error :Thenumberofv aluest oCACHEmustbegr eaterthan1.
Gener all
y,sequencesar eusedt ogener ate“ Primar ykey ”valuesaut omat i
call
y.
MUARLISI R 2015
97

Cl
assi
fi
cat
ion:
Publ
ic
Eg: SQL>cr eatesequences1
startwi t
h1;
SQL>cr eatetabletest(
snonumber(10)pri
marykey
,namev
archar
2(10)
);SQL>i
nser
tint
o
test(sno,name)v al
ues( s1.
next
val
,„&name‟)
;
Enterv aluef orname: mur al
i
SQL>/
Enterv aluef orname: abc
SQL>/
Enterv aluef orname: xy z
SQL>sel ect*f rom test;
Output :
SNO NAME
--
---
----
--
---
--
---
---
--
MURALI
ABC
XYZ

I
nOr acl
e,allsequencesi
nfor
mati
onstor
edunder“user
_sequences”dat
adi
cti
onar
y.Eg:
SQL>
descuser_sequences;
Wecanal sodr opasequenceusi
ng“
dropsequencesequencename”.
Eg:SQL>dr opsequences1;

MERGE
Oracle9i introduced“ Merge”stat
ement.Mergei sanDMLcommandwhi chisusedtotr
ansf
erdatafrom
“sourcetabl e”i nto“targettabl
e”whentablestructurearesame.
Gener al
ly,mer gest atementusedindatawarehousi ngapplicat
ions.I
nmer
gestatementweareusi
ng
update, i
nser tcommands.Thi scommandi salsocal ledas“UPSERT”command( UP-
>updat
e,SERT->inser
t).
Syntax:
Mer geintot arget tablename
usingsour cetablename
on(joi
ncondi tion)
whenmat chedt hen
updatesett arget t
abl ecol
1=sourcet
abl
ecol1,…….
whennotmat chedt hen
i
nser t
(target t
abl ecolumnnames)v al
ues(sourcetablecolumnnames);

Dat
e:8/
5/15

Eg:SQL>select*from dept;(
tar
gettabl
e)
SQL>createtabledeptsasselect*fr
om dept
;
SQL>inserti
ntodeptsv al
ues(1,
‟a‟
,‟
b‟);
SQL>select*from depts;

MUARLISI
R 2015
98

Cl
assi
fi
cat
ion:
Publ
ic
SQL>mer gei ntodeptd
usingdept ss
on(d.dept no=s. dept no)
whenmat chedt hen
updat esetd. dname=s. dname, d.
loc=s.l
oc
whennotmat chedt hen
i
nser t(d.
dept no, d.dname, d.l
oc)values(s.
deptno,s.dname, s.l
oc)
5rowsmer ged
SQL>sel ect*f rom dept ;
Through“ Mer ge”st atementwecannotupdat e“ON”cl ausecolumns.
SETOPERATORS:
Setoper at orsar eusedt oretri
evedataf r
om single(or)mul t
ipl
etabl
es.Theseoper
ator
sar
eal
socal
l
edas
“Verti
cal Joi ns”.
Union- >I tret urnsuni quev al
uesandal soautomat icall
ysorti
ngdata.
Unional l->Itr eturnsunique+dupl i
catedata.(noaut omaticsor
ti
ng)
I
ntersect- >I treturnscommonv alues
Minus- >Val uesar einf i
rstquerythosevaluesar enotinsecondquery.

Eg:
SQL>sel ectjobf rom empwher edeptno=10
union
selectjobf rom empwher edeptno=20;
NOTE:Whenev erwear eusi ngsetoperators,cor
respondingexpressi
onsmustbel ongsto
samedat atype.
Eg:
SQL>sel ectdept nofrom emp
union
selectdnamef rom dept;
Error:expr essi
onmusthav esamedat at ypeascor r
espondingexpression
NOTE:Al way ssetoper atorsreturnsfi
rstquerycolumnnames( or)al
iasnamesas“ Columnheadings”.
Eg:
SQL>sel ectdnamef rom dept
union
selectenamef rom emp;
Out put:
DNAME
--
--
----
Account ing
ADAMS
……….
NOTE:I nOr acl
e, i
ncor r
espondi ngexpressionsnotbelongstosamedat atypeal
sothenwearer etr
iev
ing
dataf rom mul ti
plequery‟susi ng“SetOper at
ors”
.Inthiscasewemustuse
appr opri
at e“Typeconv ersion”functi
on.
MUARLISI R 2015
99

Cl
assi
fi
cat
ion:
Publ
ic
Eg:
SQL>sel ectdeptnofrom emp
union
selectdnamef rom dept;
Error:expressi
onmusthav esamedat atypeascorr
espondingexpr
essi
on
SOLUTI ON:
SQL>sel ectdeptno“deptno”
,to_char
(nul
l)“
deptname”from empunion
selectto_number(nul
l),
dnamef r
om dept;
Out put:
DEPTNO DNAME
--
--
----
--
--
--
--
---
--
--
--
10
20
30
ACCOUNTI NG
SALESMAN
………………
CONVERSI
ONS:
Convert
ingonedatatypei
ntoanotherdat
aty
pei
scal
l
ed“
Conv
ersi
ons”
.
Oracl
ehav i
ng2typesofconver
sions.
Impl
ici
tconver
sions
Expl
ici
tconv
ersions

Implicitconv er
sions:
A.InOr cal e,whenanexpr essioncont ainsstr
ingr epresenti
ngpurenumber( eg:„
1234‟)thenoracl
eserver
automat i
call
yconv er
ts“St r
ingtype”i n“Numbert ype”.
Eg:
SQL>sel ectsal
+‟ 100‟fr om emp;
I
twor ks
B.InOr acle,whenev erwear epassi ngnumberi ntochar act
erfuncti
onsthenoracl
eserv eraut
omati
cally
conver tsnumbert ypeint ocharactert ype.
Eg:
SQL>sel ectl
ength( 1234)f rom dual ;
Out
put :4
C.InOr acle,whenev erwear epassi ngdat est r
ingi ntodatef unct
ionsthenoracl
eser verautomat
ical
ly
conver ts“DataStr i
ng”int o“DateTy pe”.Buthere,passedpar ametermustbein“Defaul
tDateFormat”.
Eg:
SQL>sel ectl
ast_day (‟
12- aug-05‟)fr om dual;
Out
put :31-aug-05.

MUARLISI
R 2015
100

Cl
assi
fi
cat
ion:
Publ
ic
Dat
e:9/
5/15

I
MPLI
CITCONVERSI
ONTABLE
FROM TO ASSIGNMENT EXPRESSI
ON
EVALUATI
ON
Var
char
2(or
)char Number Yes Yes
Var
char
2(or
)char Dat
e Yes Yes
Number Var
char
2(or
)char Yes No
Dat
e Var
char
2(or
)char Yes No

EXPLICITCONVERSI ONS:
Using“Expli
citconversi
ons”f unctionswecanal soconv er
tonedat atypeintoanot herdatatypeexpl
i
cit
ly.
DECODE( ):
Decode()isanconv ersi
onf unctionwhi chisusedt odecodi ngthevalues.
Decode()isalsosameas“ i
f ….then…el seif”const r
uctorinPL/SQL.Decode( )internall
yused
equali
tyoperator(=).
Syntax:
Decode( col
umnname, val
ue1, statement 1,
v alue2,stat
ement 2,stat
ement )
;
Eg:SQL>selectename, sal
,deptno, decode(dept no,
10,‟t
en‟,20,„t
wenty‟,ot
hers)from emp;
Output:
ENAME SAL DEPTNO DECODE
--
--
--
--
---
--
--
--
--
--
---
--
--
---
--
--
--
--
--
--
----
--
---
----
-
10 TEN
20 TWENTY
30 OTHERS
Using“decode()”wear edecodi ng“ number ”intostri
ng( or)“Si
nglecharacter
”intost ri
ng.NOTE:Ifwewant
tomodi f
ydatacondi ti
onal
lywi thinat ableusi ng“SQL”t henwemustuse“ Decode( )”f
uncti
on.

Wr iteaQuer ytoupdat e“comm. ”oftheemp‟ si nempt ablebasedonf ol


l
owingcondi
tion:
1.I
fjob=
„CLERK‟t henupdatecomm i nto10%ofsal .
2.Ifjob=„ SALESMAN‟t henupdat ecomm i nto20%ofsal .
3.Ifjob=„ ANALYST‟t henupdat ecomm i s30%ofsal
4.Elsecomm i s40%ofsal .
Ans:SQL>updat eempsetcomm=( decode(job,„CLERK‟ ,sal
*0. 1,
„SALESMAN‟,sal
*0.
2,„ANALYST‟,sal*
0.3,
sal*0.4));
InOr acle,ifwewantt odi spl
ayaggr egatefunctionalv al
uesi ntabularf
ormatandalsoifwewantt odispl
ay
thosev aluesconditionallyusingPI VOTING(rowsar econvertedi nt
ocolumns).
Thenwemustuse“ Decode( )”within“GroupBy ”clause.
Eg:SQL>sel ectj
ob, sum( decode( deptno,10,sal))“deptno10” ,sum
(decode( deptno,
20,sal))“dept no20”,
sum ( decode(deptno,30,sal))“depnto30”f r
om empgr oupbyj ob;
Output :

MUARLISI
R 2015
101

Cl
assi
fi
cat
ion:
Publ
ic
JOB DEPTNO10 DEPTNO20 DEPTNO30
--
----
--
---
---
---
--
-----
---
--
---
--
---
---
---
--
--
--
-----
--
---
--
----
---
--
---
ANALYST 6400
CLERK 1700 2700 1350
MANAGER 2650 3175 3050
PRESI DENT 5200
SALESMAN 5800
Eg:SQL>sel ectdname, sum( decode( job, „CLERK‟ ,1,
0))“CLERKS”sum
(decode( job,„ SALESMAN‟ ,1,
0))“ sal
esman”sum ( decode( j
ob,„ANALYST‟ ,
1,0))“anal y
st ”
from empe, deptd
wher ee. deptno=d. deptno
groupbydname;
Out put:
DNAME CLERKS SALESMAN ANALYST
--
----
--
---
---
--
---
----
----
--
---
--
---
--
--
----
--
--
--
----
ACCOUTI NG 1 0 0
RESEARCH 2 0 2
SALES 1 4 0
CaseSt atement :
Casest atemental sousedt o“Decodi ng”t hev alues.“CaseSt atement”performanceisver
yhighcompareto
decodeconv er sionf unction.Or acle8. 0,introduce“ Casest atement ”andal so“Or
acle8i
”intr
oducedcase
condi ti
onal stat ement .Thisisal socal l
edas“Sear chedCaseSt atement”.
NOTE:Decodei nternall
yused“ Equal i
tyoper at
or”(=),whereasi n“Casestatement”wecanalsouseallSQL
oper ator(<,>,<=,>=,<>,Li
ke, i
s,etc……)expl icit
ly.
METHOD1:
Sy ntax:
casecol umnname
whenv alue1t henst atement 1
whenv alue2t henst atement 2
--
----
--
---
---
---
--
-----
---
--
---
-
……………………………………………. .
elsest atement send;
Eg:SQL>sel ectename, sal,deptno, casedept no
when10t hen„ ten‟
when20t hen„ twent y

else„ others‟end
from emp;
OUTPUT:
ENAME SAL DEPTNO DEPTNO DECODE

METHOD2:( CaseCodi
ti
onal
Stat
ement(
8i)
)
Synt
ax:
MUARLISI
R 2015
102

Cl
assi
fi
cat
ion:
Publ
ic
case
whencol umnconditi
on1thenstatement1
whencol umnconditi
on2thenstatement2
…………………………………………………………………
…………………………………………………………………
el
sest atementsend;
Eg:SQL>sel ectename,sal
,
Case
whensal <1000then„LowSalar
y ‟
whensalbet ween1000and3000t hen„Medium Sal
ary
‟when
salin(3100,3200,
3500,
3800)then„ Speci
alSalar
y‟el
se„ Ot
her
Salar
y‟end
fr
om emp;
Date:11/ 5/
15

Or
aclealsohav
ingf
oll
owi
ngexpl
i
citconv
ersi
onf
unct
ions.
to_number(
)
to_char(
)
to_date(
)

to_
number ():Iti
susedt oconver
ti
nga“Str
ing”r
epr
esent
ingnumer
icv
aluewi
thf
ormati
ntonumer
ic
val
uewithoutf ormat.
Eg:SQL>select„ $45.
6‟+3from dual
;
Err
or:i
nvali
dnumber
SQL>select„45.6‟+3from dual
;
O/P:48.6
SQL>selectto_number („
$45.6‟
)+3fr
om dual
;
Err
or:I
nvali
dnumber

NOTE:Whenev erwear eusi


ng“ to_
number()
”andal soifwetr
ytoconv ert“
Str
ing”representi
ngnumeri
c
val
uewi
thformatintonumeri
cvaluewit
houtformatthenwemustuse“secondparamet er
”assameas“ f
ir
st
par
ameter
”format.Thenonl
yoracleser
verautomati
call
yconv
ert
s“St
ri
ngt ype”t
o“ Numbert ype”
.

MUARLISI
R 2015
103

Cl
assi
fi
cat
ion:
Publ
ic
Sol
uti
on:
SQL>sel
ectt
o_number
(„$45.
6‟,
„$99.
9‟)
+3f
rom dual
;O/
P:
48.
6

Notforothercharacter:
Eg:SQL>selectto_number(
„a45.
6‟,
„a99.
9‟)+3f
rom dual
;
Err
or:I
nvali
dnumberf or
matmodel

t
o_char():t
o_char(
)isan“Ov erLoading”functi
onwhichi
susedt
oconver
t“Number
t
ype”into“Charact
ertype”andalsousedt oconver
t“Dat
ety
pe”i
nto“
Charact
ert
ype”or“
Dat
eSt
ri
ng”
.
Conver
ti
ng“ Numbert ype”i
nto“Charactertype”:
Synt
ax:to_char(
number ,„
characterf
ormat ‟
)

FORMATELEMENTS:
->repr
esenti
ngNumberg- >
Groupseparator(,
)d->
DecimalIndi
cator(.
)L->Local
Currency
$->Dol l
ar($)

GroupSeparator(,)andDeci malIndicat
or(.
):
Eg:SQL>selectto_char(1234567,„99g99g999‟
)from dual
;
O/P:12,
34,567
OR
SQL>selectto_char(1234567,‟99,
99,999‟)f
rom dual
;
O/P:12,
34,567

Combinati
onofbothg&d:
SQL>selectto_
char
(1234567,
„99g99g999d99‟
)fr
om dual;
O/P:12,
34,567.
00
OR
SQL>selectto_
char
(1234567,
‟99,
99,999.
99‟)f
rom dual
;
O/P:12,
34,567.
00

Leadi
ngZer o:
Eg:SQL>selectto_char
(123,‟0999‟)f
rom dual
;
O/P:0123
SQL>selectto_char(
123,„9990))f
rom dual
;
O/P:123
SQL>selectto_char(
123,„$999‟)f
rom dual
;
O/P:$123

MUARLISI
R 2015
104

Cl
assi
fi
cat
ion:
Publ
ic
LocalCur
rency:
Eg:SQL>selectt
o_char
(123,
„L999‟
) f
rom dual
;
O/P:$123

NOTE:I fwewantt odisplayourowncur r


encythenwear eusing“ nl
s_curr
ency”parameteri
nthir
dpar amet
er
ofto“ to_char()”funct
ion.Inthiscaset hi
sparamet ermustbespeci fi
edwi t
hinsingl
equotes.Befor
ewear e
usingt hiscurrencythenwemustuse“ LocalCurrency(
L)”inthef ormatmodel ofthesecondparameter.
Eg: SQL>sel ectename, t
o_char(
sal,„
L99g99g999d99‟ ,„nls_
currency=I ndRs‟)f
rom emp;
Out put:
ENAME SAL
--
--
----
--
---
---
--
--
--
SMI TH INDRS 800. 00
ALLEN INDRS1, 400.00

Eg: SQL>sel ectename,nvl


( mgr,„
nomanager
‟)fr
om emp;
Error:Invali
dmanager
Solution:
SQL>sel ectename,nvl(
to_char(
mgr)
,„nomanager‟
)fr
om emp;
Out put:
ENAME TO_CHAR(MGR) ,„NOMANAGER‟
-
--
-----
--
---
---
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
KING NOMANAGER

Eg:SQL>sel
ectto_
char
(sy
sdat
e,„
DD/
MM/
YYYY‟
)fr
om dual
;
O/P:11/
05/2015

t
o_dat
e()
:Iti
susedt
oconv
ert“
Dat
eSt
ri
ng”i
nto“
Dat
eTy
pe”
.

Eg:SQL>select„15/AUG/05‟
+3fr
om dual
;
Err
or:Inv
ali
dNumber
Solut
ion:
SQL>selectto_dat
e(„15/
AUG/05‟
)+3fr
om dual
;Out
put
:
18/AUG/05

NORMALI
ZATI
ON

Nor
malizati
oni san“ Scienti
fi
cPr ocess”whichisusedt odecomposi ngat abl
eint
onumberoft abl
es.
Nor
malizati
onpr ocessaut omati
call
yav oi
dsinsert
ion,updati
on,del et
ionproblemsandalsothi
sprocess
r
educesduplicat
edat a.
I
ndesignphaseoft heSDLC,dat abasedesignersdesigns“LogicalModel ”ofthedat
abase.I
nthi
slogical
modelonlytheyareusi ng“Normalizati
onProcess”t
hrough“ Normal Forms”.

MUARLISI
R 2015
105

Cl
assi
fi
cat
ion:
Publ
ic
I
n1970‟s,
E.F.
CODDwr i
ttenapaper“
Rel
ati
onal
Model
Dat
aForLar
geShar
edDat
aBanks”
.Int
hispaperonl
y
E.
F.CODDint
roducedf
ir
stthr
ee“NORMALFORMS”.

NORMALFORMS:
Fi
rstNor
malForm
SecondNor
mal Form
Thir
dNormalForm
BCNF
Fourt
hNormalForm
Fi
fthNor
malForm

Dat
e:12/
5/15

FIRSTNORMALFORM(1NF):
I
fat abl
eisi
n1NF,
inthatt
abl
eeachcol
umncont
aina“
Atomi
cval
ue”andal
soi
dent
if
yingr
ecor
d“Uni
quel
y”
usi
nga“ Key
”.

Process:Ident
if
yinga“Repeat
ingGr
oups”andputitint
osepar
atet
abl
einmore“At
omicf
orm”.Bydef
aul
t,
1NFpr ocessatablei
san“Chil
dtabl
e”.Becausei
nthi
stabl
eonecol
umnhav
ingdupl
i
cat
edata.

SECONDNORMALFORM(2NF):
I
fat ablei
sin1NFandal
soal
l“Nonkeyatt
ribut
es”areful
l
yfunct
ional
lydependenton“Tot
alCandi
dat
e
Key”.Al
ways1NFdeal
swi
th“
Atomi
cit
y”wher
eas“ 2NF”deal
swit
hrelati
onshi
pbetween“KeyandNonKey
at
tri
butes”
.

MUARLISI
R 2015
106

Cl
assi
fi
cat
ion:
Publ
ic
I
fat abl
eisin1NFandal sot hattabl
econtai
nspar t
ial“NonKeyatt
ri
butes”thenthattablenoti
n“ 2NF”.
Process:Ident
if
yingpart
ialnonkeyat t
ri
buteswhichdependson“ Parti
alKeyat tri
butes”putintosepar
ate
tabl
e.Thistabl
eiscall
ed“ 2NF”table.Bydefaul
tthi
st abl
eisan“Mastertable”
.Inthist
ableonlyall“
NonKey
attr
ibut
es”are“Full
yFunctional
lydependentontotalcandi
datekey”
.

Dat
e:13/
5/15

MUARLISI
R 2015
107

Cl
assi
fi
cat
ion:
Publ
ic
Phase1:
1.Ecode- -
- (<--- FD-
--
- )--
-  Hours(Worng)E101-
- 4,
9
2.Projcode--
-- ( <-
--FD--
-)-
 Hour
s(Wrong)P1- 4,
5,7
3.Ecode+Proj
code- -
-  Hour
s(Corr
ect)
F->Full
yFunct ionalDependent

Phase2:
1.Ecode--
-- (<--- FD - -
-)
-- Dept
(Corr
ect)E101-
- Systems
2.Proj
code--
--
- (
<--
-FD---)-
 Dept(Wrong)P1--
 systems,sales,admin
Oncepart
ialdependenciesissati
sfi
edwewantt ogof or“
FullyFuncti
onalDependent
”.

Phase3:
1.Ecode-
--
- (<--
- FD -
--
)-
- Dept
head(
Cor
rect
)
MUARLISI
R 2015
108

Cl
assi
fi
cat
ion:
Publ
ic
2.Pr
ojcode-
- Dept
head(
Wrong)

Dat
e:14/
5/15

BeforeNor mal izationpr ocessi ntheabov eresear chhav i


ngInsert
ion,Updati
on,Del eti
onpr oblems.
Inserti
onPr oblem:I nt heabov eresour cetablewhenwear etryi
ngt oi
nsertparti
cul ardepartmentempl oyee
thenwemustassi gnpr ojectcode.I fprojectcodei snotav ail
abl
et henweneedt osuppl ynullv aluesforthe
projectcodef i
el d.Thi siscal l
ed“ I
nser ti
onPr oblem” .
Updat ion Probl em:I nt he abov er esouce t abl
e ecode,dept ,dept head at
tributev alues ar er epeat
ed.
Whenev erresour cet ablehav i
ngl argeamountofdat aandal sowhenwear emodi fyi
ngdat at henwemust
changet heset hreev aluescor r
ectly.Ot herwise,Inconsist
encyPr obl
em occur s.Thi siscal l
ed“Updat ion
Problem” .
DeletionPr oblem:I ntheabov er esourcet ablewhenwet rytodeleteaempl oyeer ecordt henaut omati
call
y
depar mentdet ai l
sal sodel et
ed.Thi si scalled“ Deleti
onPr obl
em” .Wheneverwear eusing“ Nor mali
zat
ion
Process”t henaut omat icall
yInser ti
on,Updat ion,Delet
ionproblemsav oided.
Wi thoutusi ngNor mal izati
onPr ocess

Dat
aRedundancyPr oblems
Discspacewast ed
DataInconsi
stency
DMLOper ati
onsbecomeslow

MUARLISI
R 2015
109

Cl
assi
fi
cat
ion:
Publ
ic
ATablei
sin“ 1NF”
:
1.Datai
neachcolumnshouldbeat omi
c:
I
stherei
snomul ti
pleval
uessaperatedbycolumn(,)
.
Tabledoesnotcontai
nrepeati
ngcolumngr oups.
Ident
if
yingarecorduni
quel
yusi nga“Pri
maryKey ”
.

1.

2.
SOLUTI
ON:

Dat
e:15/
5/15

THI
RDNORMALFORM(
3NF)
:

Ifatablei
san2NFandal soallnonkeyatt
ributesareonlydependenton“Candi
dat
ekey”.
Ifatableisi n2NFandal so“NonKeyAt t
ributes”whichdependentsonanother“
NonKeyAt t
ri
but
es”t
hen
thattabl
enoti n“3NF” .
Process:I denti
fyi
nga“ NonKeyat t
ri
butes”whi chdependsonanot her“NonKeyat t
ri
but
es”butint
o
saperatetable.Thistabl
eiscall
ed“3NF”table.Bydefaultt
histabl
eisan“Mastert
abl
e”.I
nthi
stabl
eonl
yall
“Nonkeyat t
ri
butes”areonlydependenton“CandidateKey”.

MUARLISI
R 2015
110

Cl
assi
fi
cat
ion:
Publ
ic
LOGI
CALDI
AGRAM:

DATE:16/
5/15

1NF-
>Remov
eRepeat
ingGr
oups

MUARLISI
R 2015
111

Cl
assi
fi
cat
ion:
Publ
ic
2NF-
>Remov
ePrati
alAtt
ri
but es
3NF-
>Remov
eAttr
ibut
eswhi charenotdependentonCandi
dateKey.
(
OR)
Remov eNon-KeyAt t
ri
but
ewhicharedependentonanot
herNon-
KeyAt
tri
but
e.

CLUSTERS

Clusteri
san“ Dat abaseObj ect”whichcont ai
nsgroupoftabl
est ogetherandi twi
ll
“SharessameDat a
Blocks”.
Gener al
l
y ,
clustersar eusedt oimprovesper f
ormanceonly.
I
nal ldatabasecl usterstabl
esmusthav ea“ CommonCol umnName” .Thi
scommoncol umnsisalsocal
led
as“ Cl
usterKey” .
I
nal ldatabases,whenev erwear esubmi t
ti
ng“ I
nnerJoi
n”(or)“OuterJoin”thendatabaseserv
erschecks
“FROM”cl auset ablesar eavail
ableinclust
ers(or)not
.
I
ft hosetablesar eav ai
labl
einclusterthendatabaseserver
sr et
rievedataveryfastl
yfrom t
he“Clust
er
Tables”.

Cr
eat
ingClust
ers:
St
ep1:Cr
eateaCluster
St
ep2:Cr
eateanIndexonClust
er
St
ep3:Cr
eateClust
erTabl
es.

St
ep1:Creat
eaClust
er:
Cl
ust
ersarecr
eat
edbasedoncommoncol
umn.Thi
scommoncol
umni
sal
socal
l
edas“
Clust
erKey
”.

MUARLISI
R 2015
112

Cl
assi
fi
cat
ion:
Publ
ic
Sy
ntax:cr
eat
ecl
ust
ercl
ust
ername(
commoncol
namedat
aty
pe(
size)
);

St
ep2:Creat
eanI ndexonClust
er:
Sy
ntax:cr
eat
eindexindexnameonclust
ercl
ust
ername;

St
ep3:Cr eateClusterTables:
Synt
ax:
cr
eatetablename(commoncol namedat
aty
pe(
size)
,col
1dat
aty
pe(
size)
,….
)
cl
uster
cl
uster
name( commoncol name);

Eg:
Sql>createcl ust eremp_ dept(dept nonumber (10));Sql>
cr
eatei ndexi n1oncl usteremp_ dept ;
Sql>cr eatet ableemp1( empnonumber (
10),enamev archar 2(
10),
salnumber(10),deptnonumber(
10))
cl
usteremp_ dept (deptno);
Sql>cr eatet abledept 1(dept nonumber (
10), dnamev ar char2(
10),l
ocvar
char2(10))cluster
emp_ dept (dept no);
Sql>descemp1;
Sql>descdept 1;
Sql>inser tintoemp1v alues( 1,„abc‟,2000, 10);
Sql>inser tintodept 1values( 10, „
xyz‟,„hyd‟);
Sql>sel ect*f rom emp1;
Sql>sel ect*f rom dept 1;
NOTE:I nal ldatabasesy stem cl ustertableshav ingsome“ Rowid‟
s”.
Eg:sql >sel ectr owidfrom emp;
Sql>sel ectr owidf rom dep1;
Gener all
y,wecannotdr opcl usterifclusterhav i
ngt ables.Toov er
comethisproblem Or acl
e8i
int
roducedt
o
dropcl usteral ongwi t
ht ablesusi ng“ I
nclusingt abl
es”cl ause.
Syntax:
Sql>dr opcl ustercl usternamei ncludingtables;
Eg:sql >dr opemp_ deptincludingt ables;
Clusterdr opped;

Dat
e:18/
5/15

I
nOracleal
l Cl
uster
sinfor
mati
onstordunder“
user
_cl
ust
ers”dat
adict
ionary.
I
nallrel
ati
onaldatabasesusi
ngCluster
swecanachievephysi
caldataindependence,becausewhenev
er
weareaddingclust
erstabl
estr
uct
uredoesnoteff
ect
sbutonlyper
formanceiseffectedwhenwear eusi
ng

joi
ns”.

Candidat
eKeys:
Empno+ski
ll
Ename+ski
ll
MUARLISI R 2015
113

Cl
assi
fi
cat
ion:
Publ
ic
3.Vot
eri
d+ski
l
l

SUPERKEY:Acol umn( or)combinati


onofcolumnswhichuniquelyi
ndenti
fyi
ngarecordinatabl
eiscal
led
“SuperKey”.
CANDI DATEKEY:Ami nimal“SuperKey”whichuni
quelyi
dentif
yingarecordinatabl
eiscall
ed“Candi
date
Key ”
(or)
A“ SuperKey”whi
chdoesnotcont ai
nsanot
her“SuperKey”i
salsocall
edas“ Candi
dateKey”
.

FUNCTIONALDEPENDENCY( FD):
I
fanygiventwotupl
esinarel
ation“r”t
henifX(anattr
ibut
eset)agreest
henY(anotherat
tri
but
eset)cannot
di
sagreethenonl
yX->Yiscal
led“Functi
onalDependency”
.X->YhereYisFuncti
onall
yDependentonX
Xfuncti
onall
ydet
erminesY.(
hereXi sal
socalleda“Deter
minent”andYisalsocal
ledas“Dependent
”)

BCNF:WhenatableisinBCNFthenever
ydetermi
nanti
sa“ Candi
dat
eKey ”.
Whenat abl
econtainsmult
ipl
ecompositecandi
dat
ekeysandal sothosecandidat
ekeysareover
lapped
andalsoonecandidat
ekeynonkeyat t
ri
buit
ewhichdependsonanot hercandi
datekeynonkeyat
tri
bute
thenonl
yweareusingBCNFprocess.

General
l
y,whenatabl
econtainsmult
ipl
ecomposi
tecandi
dat
ekeysthendel
eti
onproblem occur
redt
o
over
comethispr
obl
em dat
abasedesi
gner
suses“
BoyceCodeNormal
Form”i
ndatabasedesi
gn.

Gener
all
y,secondandt
hir
dnor malfor
msdealswithrel
ationshi
pbetweenkeyandnonkeyat tr
ibut
es.
WhereasBCNFdealswi
threl
ati
onshi
pbetweennonkeyat
tri
buteswit
hincomposi
tecandi
dat
ekey
sitsel
f.

PROCESS:I
denti
fyonecomposi tecandi
datekeynonkeyatt
ri
buteswhi
chdependsonanothercomposit
e
candi
dat
ekeynonkeyat tr
ibutesputint
osaperat
etabl
e.Thi
stablei
salsocal
ledas“BCNFt abl
e”.I
nthi
s
tabl
eonlyever
ydeterminantbehav esli
keacandidatekeyandalsointhisBCNFt abl
e.Therelikea
candi
dat
ekeyandalsointhisBCNFt abl
e.Ther
eisnononkeyatt
ri
but
es.

MUARLISI
R 2015
114

Cl
assi
fi
cat
ion:
Publ
ic
NOTE:I
fat
abl
econt
ainssi
ngl
ecomposi
tecandi
dat
ekeyt
henBCNFi
sal
sosameas3NF.

Dat
e:19/
5/15

MULTIVALUEDDEPENDENCY:
I
nat able,i
fadeterminantdet
erminesmulti
plevaluesinanot
hercol
umnwi t
hinsametabl
ei scal
l
ed

Mult
ival
ueddependency”
.Mult
ival
ueddependencyr
epresent
edbyusi
ngDoubl
eArrowmar
ks(“-
>->”
).
Singl
eValueMulti
pleCol
umns

FOURTH NORMALFORM( 4NF):I fat ableisin4NFt henthattabledoesnotcontainmor ethanone


i
ndependentmult
ival
uedattri
butes.
I
fat ablecont
ainmi ni
mum t hree(3)attri
butesandalsousingcombi nat
ionallt
heseat t
ri
butesuniquel
y
i
denti
fi
cati
onoftherecordandal sooneat tr
ibut
esetofv al
ueswhichdependsonanot heratt
ri
butesetof
val
uesandalsosameat tr
ibutesetofv alueswhichdependsonanot herat
tri
but
esetvaluesandalsosome
att
ri
butesar
enotlogi
call
yr el
atedt henonlyweareusing4NFprocess.

PROCESS:I
dent
if
yi ndependentmul
ti
valuedat
tri
but
esputi
tintosaper
atetables.Thesetabl
esar
ecal
l
ed
4NFtabl
est
hesetablesdoesnotcont
ainmorethanonei
ndependentmul
ti
valuedattr
ibut
es.

MUARLISI
R 2015
115

Cl
assi
fi
cat
ion:
Publ
ic
General
ly
,whenat abl
econt ai
nsmorethanonei ndependentmul
ti
valuedatt
ribute.Thent hoset abl
es
havi
ngmor edupli
catedat
atoov er
comethispr
oblem forreduci
ngdupl
icatedat
at hendatabasedesigners
uses4NFpr ocessinthisprocessonetabledoesnotcont ainmorethanonei ndependentmul tiv
alued
att
ri
bute.
ASSUMPTI ON:Eachemployeehasmult
ipl
eproject
sandal soeachempl
oy eehavi
ngmul ti
pleskil
ls.

I
ntheaboveresourcet
ablewheneveranempl
oyeegotanewprojectt
henwehavetosuppl
ynullval
uesfor
t
heskil
lat
tri
buteandalsowheneveranemployeegotnewskil
lthenwehavetosuppl
ynullv
aluesforthe

proj
ecti
d‟att
ribut
e.Thesenul
lval
ueprobl
emsareautomat
ical
l
yav oi
dedwhenweareusi
ng4NFpr ocess.

FIFTHNORMALFORM( 5NF):
I
far elat
ioncannotbedecomposedi ntofur
therrel
ati
onsiscalled5NFi.
e.,i
fat abl
eisin5NFthet abl
e
doesnotcontai
nscycl
i
cdependencies.
Generall
y,i
fatabl
econtainsmorethantwoattr
ibut
esandalsoidenti
fyi
ngarecordusi
ngcombinat
ionofall
theseattr
ibut
esandalsoal lt
heseatt
ri
butessetofvaluesrel
atedtooneanot hert
henonl
ywear eusing
5NF.

NOTE:Whenatabl
econt
ainsmulti
val
uedat
tri
but
esandalsosomeatt
ri
but
esarenotl
ogical
l
yrel
atedwhen
t
h
onl
ywear eusing4 NFpr ocesswhereaswhenat abl
econtai
nsmulti
val
uedattr
ibut
eandal soal
l
t
h
at
tri
but
esar
elogi
cal
l
yrel
atedt
henonl
ywear
eusi
ng5 NFpr
ocess.
TH t
h
5 Nor malFormisalsocal
ledas“Pr
oject
ionJoi
nedNormalFor
m”becausein5 NFi fpossi
blet
henwe
candecomposingatablei
ntonumberoftabl
esbutwhenwearejoi
ningt
hosetabl
est
henresult
antrecor
d
mustbeavai
lablei
nresour
cetabl
e.

Eg:

ORACLESERVERARCHI
TECTURE

MUARLISI
R 2015
116

Cl
assi
fi
cat
ion:
Publ
ic
Oracleser v
ermainlyconsi
stoft
wopar ts:
StorageAr ea
Instance
StorageAr ea:Wheneverweareinstal
l
ingor
acl
eserverautomatical
l
ythr
eephy
sical
fil
esar
ecr
eat
edi
n
harddiskthesefil
esarecall
edasStorageArea(
or)Phy
sicaldatabase.
Dat afil
es(.
DBF)
Cont r
ol f
il
es(.
ctl
)
Redol ogfi
les(
.l
og)

LogicalStr
ucture
PhysicalStr
ucture

LOGICALSTRUCTURE:Ast r
uct
urewhichisnotvi
sibl
einoperati
ngsystem i
scall
ed“LogicalSt
ruct
ure”
.
-
>Logical
str
uct
urecont
ainsdat
abaseobject
sli
ketable,
views,synony
ms, cl
uster
s,sequences.
-
>Logical
str
uct
urei
shandledbyeit
herdevel
oper
s( or
)databaseadminist
rat
ors.

PHYSICALSTRUCTURE:Ast ruct
urewhichisvi
sibl
einoper
ati
ngsyst
em i
scall
edPhysi
calst
ruct
ure.
Physi
calst
ruct
urecontai
nsdataf
iel
s,cont
rolf
il
es,r
edologf
il
es.-
>Physi
calst
ruct
urei
shandl
edby
dat
abaseadminist
rat
oronly
.

Dat
e:20/
5/15

Dat
aFiles:Dat
af i
l
esst oresdatabaseobjectsphy
sical
lythatisthesefi
lesstor
establ
es,
views,
sequences,
i
ndexespermanentlyint
ohar ddiskthesefi
lesext
ensionis“.dbf”.
->I
nOracleall
datafi
lesinfor
mat i
onst or
edunder“dba_data_fi
les”dat
adicti
onary
.
Eg:sql
>connsy sasdba
Ent
erpassword:sys
MUARLISI R 2015
117

Cl
assi
fi
cat
ion:
Publ
ic
Sql>descdba_ data_ f
il
es;
Sql>selectfi
le_namef rom dba_data_ f
il
es;
CONTROLFI LES:Cont rolfi
lescontrolsall
otherfi
l
eswithi
nstor
ageareathesefi
l
esextensioni
s“.ctl
”.
->Controlfi
lesal sost roesphysicaldatabaseinf
ormati
onthesefi
elsar
eusedbydat abaseadminist
rat
ori
n
backupandr ecov eryprocess.
->I
nOr acle,allcontrol fi
l
esinformationstoredunder“
v$cont
rolf
il
e”dat
adicti
onary
.Eg:sql>desc
v$controlfi
le;
Sql>selectnamef r
om v $contr
ol f
il
e;

REDOLOGFI LES:Redol ogf i


l
esstorescommi t
eddatafrom t
heredologbuf
fer
.Redol
ogf
il
esal
sousedby
databaseadmi nist
ratorinbackupandrecover
yprocess.
->I
nOr acle,
alllogfil
esinformati
onstoredunder“
v$logf
il
e”dat
adict
ionar
y.Eg:
sql
>
descv $logfi
le;
Sql>sel ectmemberf r om v$l
ogfi
l
e;

INSTANCE:Whenev erwear eper f


ormi nganyoper at
ionswi t
hindatabasethoseal
loperati
onsalsof i
rst
perf
ormedi nPhy si
calmemor yarea.ThisPhy si
calMemor yareaisalsocal
ledas“I
nstance”
.ThisInst
ance
i
sav ai
labl
einRAM memor yareathisinstancehavingt
wopar ts.
SGA
Processes
SGA:SGAi salsocalledasSystem Global Ar
ea(or)SharedGlobalAr
ea.SGAmemor yareaconsistofsetof
buff
erstheseare
Databasebuffercache
Sharedpool
Javapool
Largepool
Redologbuffer

->Whenev erwear esubmi tti


ngsql ,pl/sqlcodet hatcodei sstoredi nlibr arycachewi t
hinshar edpool
Librarycodeal waysr educespar sing.Librarycacheal sost orescachev al
uesdef i
nedi nSequencedat abase
object.
->Shar edPoolal socont ainsdi ct
ionarycachewhi chexecut es“dcl”r elat edobj ect
sandal sochecks
usernameandpasswor dsgiv enbyt heclientconnectt ot heser ver
.
->Whenev erwear er equestingat ableusi ngacl i
entt oolt henser verpr ocessal wayschecksr equested
tableisav ai
l
abl eindat abasebuf fercahce.I frequestedt ablei snotav ai
labl ei nbuffercachet hendbwr i
ter
processchecksr equest edt abl
ei sav ail
ableindat af iles.Ifr equestedt ablei savail
ableindat af i
lesthen
copyoft het abletransf er
redi ntodat abasebuf fercache.Thenonl yser v erpr ocessf et
chingt hatt able
i
nf ormati
onf r
om dat abasebuf fercachei ntocli
entt ool.
->Jav aPoolexecut esj avar el
at edobj ectsandal sol argepoolper formsl argenumberofoper ationsand
alsoredologbuf ferstorednewi nfor mationf orthetransact ion.

MUARLISI
R 2015
118

Cl
assi
fi
cat
ion:
Publ
ic
UNDO:I n Oracle,when wear eperfor ming dmlt ransactionst hen new val
uesf orthet ransact
ion is
automatical
l
yst oredindi rt
ybuf f
erwithindat abasebuf f
ercacheandal sooldvalueforthet r
ansacti
oni s
automatical
l
yst oredi nundoar eawithinbuf fercahce.Whenev eruserusingcommi t.Thenaut omaticall
y
new valuefort het ransactionisstoredi ndat af i
leswi thinstorageareaandal sool dv aluesfort he
tr
ansactioni
saut omat i
callystor
edinUNDOf ilewithi
nst oragearea.
->InOr acle9i,onwar dswecanal so r etr
ieveacci dentaldataaf tercommitingthet ransacti
onusi ng
fl
ashbackqueriest heseflashbackqueriesinternal
lyusesUNDOf i
l
e.

Dat
e:21/
5/15

REDO:Whenev erwear eperformingtransactionsnew val


ueforthetr
ansact
ioni
sautomat i
cal
lystor
ing
“Redol
og”buff
er.Whenev er“User
”using“ Commi t(or
)1/3fil
lofRedol
ogbuff
er”t
heRedol ogbuff
erdata
automati
cal
l
yt ransfer
red i
nto Redol
og files.These Redol
og fi
l
esused bydatabase admini
str
atorin
backupsorr
ecov er
yprocess.

MUARLISI
R 2015
119

Cl
assi
fi
cat
ion:
Publ
ic
PROCESSESS:Or acleInstancei
nter
nal
l
yhav
ingf
oll
owi
ngbackgr
oundpr
ocesses.Thesear
e:
Dbwr(
dat abasewr it
er)
Lgwr
(logwr it
er)
Ckpt
r(checkpoi nter)
Pmon(processmoni tor)
Smon(system moni tor)

DBWR:Dbwrpr ocessf et chesdat afrom databasebuf fercacheandst orethatdataindatafileswithi


n
stor agearea.
LGWR:Lgwrpr ocessf etchesdat af r
om Redol ogbufferandt hatdatastoredinto“Redologfi
les”.
CKPTR:Whenev erdat abasewr i
terperform somet askt hencheckpoi nterautomat i
call
ygeneratesan
uni queidentifi
cationnumberf oreverytransact i
on.Thi snumberi sautomat i
call
ystoredindat af i
l
es,
cont rolfi
l
es, Redologf il
es.Thisnumberi sal socalledas
Sy stem ChangeNumber ( SCN).Thisnumberi susedbydat abaseadmi nist
ratori
n“ Fl
ashBackQuer ys”
.
FlashBackquer ysr etriev esaccidentaldat abasedonaspeci fi
cpoi ntoft i
me.Af tercommi ti
ngt he
tr
asact ionsonl yin“Fl ashbackquer i
es”wear eusingasofcl auses.
Sy ntax:
Sql >select*f r
om t abl enameasofscnsy stem changenumber ;
Wecanal sov i
ewsy stem changenumberusi ng“curr
ent _scn”propert
yfrom “v$database”data
dict i
onaryinsy sasdbauseronl y.
Eg:
Sql > conn sy s as sy sdba
Ent erthePasswor d: sy s
Sql >createtableb1( snonumber (10);Sql
>
descv $database;
Sql >selectcurrent_scnf r om v$database;
Out put:
CURRENT_ SCN
--
-----
--
--
--
--
-
1012963
MUARLISI
R 2015
120

Cl
assi
fi
cat
ion:
Publ
ic
Sql
>insertint
ob1v alues(50) ;
Sql
>commi t;
Sql
>selectcount(*
)from b1;
Output
:1
Sql
>selectcount(*
)from b1asofscn1012963;
Output
:0
PMON:Pr ocessmoni torcleansupuserpr ocessesifusersdoesnotdisconnectproper
lyf
rom t
he
ser
ver.
SMON:Sy stem monitorprocessr ecover
yallprocesses.Wheneverproblemsar eoccur
red
i
nanpr ocess.That‟
swhysy stem monit
orisalsocall
edas“ I
nst
anceRecov ery”
.

InOracl
e,ser
verpr
ocesscont
ainsamemor
yareawhichuniquel
yindent
if
iedbyeachcli
entconnectt
othe
ser
ver.Thismemoryareaisalsocal
l
edas“Pr
ivat
eGlobalArea”.I
npl/sqlal
lconnect
ionsareexecut
ed
wit
hinPGAmemor yarea.

InRelati
onalDatabaseswecanal sostoreshier
archicaldata.Ifyouwanttostor
ehierar
chicaldatathen
minimum threecolumnsrequir
edinat able.Andalsointhoset hr
eecolumnstowcolumnsmustbel ongsto
samedat at ype.Andal so havi
ngsomer el
ati
ont heset wo columnsarealso cal
ledas“ Hier
archical
Columns”.
Ify
ouwantt or et
ri
evehier
archi
caldatafrom arel
ationalt
ablethenwear eusi
ngfol
l
owingclauses.
Level
Star
twith
Connectby

LEVEL:Leveli
saPseudocolumnwhi chaut
omaticall
yassi
gnsnumber
stol
eveli
natreestr
uct
ure.
Level
sarealsost
art
ingwithLevel
number“1”(one).
STARTWI TH:Usi
ng“ St
artwi
th”cl
ausespeci
fi
esst ar
ti
ngcondi
ti
onwit
hint
reest
ruct
ure.

Dat
e:22/
5/15

Synt ax:startwithconditi
on
CONNECTBY:Usi ng“ConnectBY”clausewearespeci
fyi
ngr
elat
ionshi
pbet
weenhi
erar
chi
cal
col
umns
using“ Pri
or”operator.
Synt ax:connectbypr iorparentcol
umnname=chil
dcolumnname;
Synt ax:
selectlevel,columnnamef r
om tabl
ename
wher econdi ti
on
startwi t
hcondi ti
on
connectbypr iorparentcol
name=childcol
name;

Wri
teanhier
archi
cal
querytodi
spl
ayt
heempl
oyeeswhoar
ewor
kingunderot
herempl
oyeesr
out
e
nodeonwardsfr
om empt abl
e?
ANS:
MUARLISIR 2015
121

Cl
assi
fi
cat
ion:
Publ
ic
sql>selectlevel
,enamefr
om emp
Startwithmgri snull
Connectbypr iorempno=mgr
;
OUTPUT:
LEVELENAME
--
--
----
---
--
--
-
KING
JONES
SCOTT
ADAMS
FORD
SMITH
BLAKE
ALLEN
WARD
MARTI N
TURNER
JAMES
CLARK
MILLER

NOTE:Or acle9i,i
ntroduced“sys_connect _
by_path()”funct
ionwhi
chretur
nspat
hofthehi
erarchyi
ntree
structure.Thisfunctionacceptstwopar ameters.
Syntax:
Sys_ connect_by_path(col
name,‟deli
mitername‟ );
Eg:
sql>sel ectl
evel,sys_connect_
by_path(ename,‟->‟)
fr
om emp
startwithmgri snul l
connectbypr i
orempno=mgr ;
Wr i
teahierarchicalquer
ytodi spl
ayt heempl oyeeswhoar eworki
ngunder“
BLAKE”f
rom emptable?
ANS:
sql>sel ectl
evel,sys_connect_
by_path(ename,‟->‟)from
emp
MUARLISI R 2015
122

Cl
assi
fi
cat
ion:
Publ
ic
startwithename=‟ BLAKE‟
connectbypr i
orempno=mgr ;
OUTPUT:
LEVEL ENAME
--
---
---
--
--
--
--
--
1->BLAKE
2->BLAKE- >ALLEN
2->BLAKE- >WARD
2->BLAKE- >MARTI N
2->BLAKE- >TURNER
Eg: sql
>sel ectl
evel
,sys_connect
_by
_pat
h(ename,
‟-
>‟)
fr
om emp
startwithename=‟ BLAKE‟
connectbyempno=pr i
ormgr ;
OUTPUT:
LEVELNAME
--
---
---
--
--
--
--
1->BLAKE
2->BLAKE- >KING

PRI OR:Priorisan“ Unar


yOper ator”usedalongwith“ConnectBy”clause.Whenwear eusingpr ioroper
ator
i
nfrontoft hepar entcol
umn( mgr )thenoracleser
verusesbottom toupsear chwithintr
eest ructur
ewher e
aswhenwear eusi ngpri
oroper atorinf
rontofthechildcolumnt henor acl
eser verusest opt obottom
sear chwithi
nt r
eest r
uct
ure.
EXECUTI ON:Basedont he“ St
artwi t
h”conditi
onoracl
eservertakea“ Pri
or”oper
atorcolumnv al
ueandt hat
valuei ssearchinginanotherhierarchi
calcolumn.Thenonlycor r
espondingcolumndat ar et
rievefrom the
table.

Cr eateahi erarchicalt
abl
ebasedont hefol
l
owi
ngtr
eestructur
e?ANS:
Sql>createt abletest(enamev archar
2(10),
empnonumber
(10),mgrnumber
(10)
);Sql
>inser
t
i
ntot estv al
ues( „
anand‟ ,
6000,8000);
Sql>sel ect*f r
om t est;
OUTPUT:
ENAMEEMPNOMGR
--
--
---
--
---
---
---
---
--
--
---
---
--
---
ANAND60008000
MILLER 6001 8000
ANIL 8000 9000
JAMES 8001 9000
SMI TH 9000 10000
JONES 9001 10000
MURALI 10000 NULL
201
MUARLISI
R 5
123

Cl
assi
fi
cat
ion:
Publ
ic
Mai
nly
,threecondit
ionstobui
l
dhierar
chicalt
able:
Tablemustcont ai
n3columns
Onecol umnmusthav ea“NULL”value(
forrootnode)
Anyt wocol umnsmustbesamedat atypeandi nter
rel
ated(
i.
e.,onecolumnallv
aluesmustbein
anothercolumnf orexample“mgr”columni spar entcol
umnand“ empno”col
umnischil
dcolumn
becauseparentcolumnconsi
stof“NULL”v al
ue)

NOTE:Whenev erwear eusing“OrderBy”cl


auseinhierarchicalquer
y‟sdat
abaseserver
ssort
ingthedata
butchangest hehierarchi
calstr
ucturewi
thi
nt r
eestructure.Toov er
comethisprobl
em Oracl
eint
roduced
“OrderSibli
ngsBy”clausewithi
nhierar
chi
calquery
‟s.
Syntax:
ordersi
blingsbycolumnname[ asc/
desc]
Eg:
Sql>selectlev
el,
ename
fr
om emp
startwi
thmgri snull
connectbypr i
orempno=mgr
ordersi
blingsbyename;

NOTE:Or acle10g,i
ntroduced“connect
_by_r
oot
”oper
atorwhi
chr
etur
nsr
ootnodei
nthehi
erar
chy
.
Syntax:connect _
by_rootcolumnname;
Eg:
Sql>sel
ectl evel
,ename, connect
_by_r
ootenamefr
om
emp
startwithmgri snull
connectbypr i
orempno=mgr
ordersibli
ngsbyename;

Dat
e:23/
5/15

TRANSACTI ONCONTROLLANGUAGE( TCL):


Transct
ion:Al
ogical
uni
tofwor
kinbetweent wopoi
ntsi
scal
l
ed“
Transact
ion”
.
Al
l dat
abasesyst
emshaving2t
ransact
ional
command.
MUARLISI
R 2015
124

Cl
assi
fi
cat
ion:
Publ
ic
Commit
Sav
epoi
nt

COMMI T:Thi scommandi susedt osavet hetr


ansactionpermanentl
ytodat
abase.Syntax:
commi t;
SAVEPOI NT:Al ogi
cal mar kbetweent r
ansacti
onsiscal l
ed“Savepoi
nt”
.
Syntax:savepoi ntsavepointname;
ROLLBACK:Thi scommandi susedt o“UNDO”t hetransacti
onsfrom memor
y.Syntax:
rol
lback;
ROLLBACKTOPERTI CULARSAVEPOI NT:Syntax:
rol
l
backt osav epoint
name;
Eg:Sql>inser tint
oemp( empno)v al
ues(1)
;
Sql>updat eempsetsal =sal+100wher eename=‟SMI TH‟;
Sql>savepoi nts1;
Sql>insertintoemp( empno)v alues(2)
;
Sql>updat eempsetsal =sal+100wher eename=‟KING‟;
Sql>savepoi nts2;
Sql>deletef r
om empwher eempno=2; Sql>
rol
lbacktos1;
Sql>commi t;
Sql>select*f rom emp;

NESTEDTABLE:
Oracle8.0,
introducednestedtabl
e.Atablewithinanothertableisal
socall
edas“ NestedTable”
.Basicall
y,
nestedtabl
ei sanuserdef i
neddat
atypewhichisusedt ostorenumberofdataitemsinasi ngl
eunit
.
General
ly,i
fwewantt ostorenumberofdat ai t
emsi nasi ngleunitt
henwear eusi ngIndexbytablein
PL/SQL.Butt heset abl
esarenotall
owedt ost orepermanent l
yint
odatabase.Toov ercomethi
spr oblem
Oracle8.0intr
oducedext ensi
onoftheIndexbyt ablescall
ed“ Nest
edTable”whichstoresnumberofdat a
i
temsandal sothesetablesar
eall
owedt ostor
eper manentlyintoor
acledat
abaseusingSQL.

CREATI
NGNESTEDTABLE:
St
ep1:creat
eanObj
ectt
ype.
St
ep2:creat
eanNest
edtablet
ype
St
ep3:creat
eanAct
ualt
able.

Step1:Cr eat eanObj ectType:


ObjectTy pe: Objectt
ypeisanuserdef i
nedtypewhichstoresdif
ferentdat
aty
pesi
ntosi
ngl
e
unit.Itisal sosameas“ Str
uctures”i
n“Clanguage”.
Synt ax:
creat eorr eplacetypetypename
asobj ect(attri
bute1datatype(
size),
att
ri
bute2datat
ype(si
ze),
…….);
Step2:Cr eat eanNest edTableTy pe:
MUARLISI R 2015
125

Cl
assi
fi
cat
ion:
Publ
ic
CreateanNest edtabletypebyusi
ngObj ectt
ype.
Syntax:
Createorreplacet ypetypename
astableofobj ectty
pename;
Step3:CreateanAct ualTable:
Syntax:
createt
abletabl ename(col1datat
ype(
size),
….,
col
nnest
edt
abl
ety
pe)
nestedtablecol nstoreasanyname;

Eg:sql>createorreplacet y
peobj1
asobject(bookidnumber (10),
booknamevar
char
2(10),pr
icenumber
(10)
);
/
Sql>createorreplacetype
abcast ableofobj;
/
Sql>createtablestudent(
snonumber (
10)
,snamevarchar2(
10),
col
3abc)nest
edt
abl
ecol
3
stor
easzzzz;
TableCreated.
Sql>descst udent
;
NAME TYPE
--
--
--
--
--
---
--
---
--
--
SNO NUMBER( 10)
SNAME VARCHAR2( 10)
COL3 abc

I
fwewanttost
oredat
aint
onest
edt
abl
ety
pet
henwemustuseconst
ruct
or.Her
econst
ruct
ornamei
s
al
sosameasty
pename.

I
NSERTION:
Sql
>inserti
ntostudentval
ues(
1,‟
mur
ali
‟,
abc(
obj
1(101,
‟j
ava‟
,900)
,obj
1(102,
‟pl
sql
‟,
500)
));
1rowcr
eat
ed.
Sql
>select*from st
udent;

Wecanal sor et
ri
evemodi f
ydelet
enestedt abl
edat asaperat
elybyusi
ngtabl
eoper
atori
.e.
,i
npl
aceoft
abl
e
namewear eusingfoll
owingsynt
axinselect,update,del
etestat
ements.
Syntax:
tabl
e( sel
ectnestedtabl
ecolnamefr
om relati
onaltabl
ename) ;

MUARLISI
R 2015
126

Cl
assi
fi
cat
ion:
Publ
ic
Eg:
sql
>sel
ect*f
rom t
abl
e(sel
ectcol
3fr
om st
udent
);

OUTPUT:
BOOKID BOOKNAMEPRI CE
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
101 JAVA 900
102 PLSQL 500.

Eg:sql
>updatetable(
selectcol
3fr
om st udent
)setpr
ice=1000wher
ebooki
d=101;
OUPUT:
BOOKID BOOKNAME PRICE
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
101 JAVA 1000

Dat
e:25/
5/15

PARTI
TIONS

Parti
ti
ons:Att het i
meoft ablecreati
onat abl
ecanbedecomposedi ntonumberofpar ti
onsiscalled
“Part
iti
onTabl e”.Parti
ti
onTabl esareusedi ndat
awarehousingapplicat
ions.Partit
ionTabl
esarecreated
bydat abaseadmi nist
ratorandusedi nbackupandrecoveryprocess.Parti
ti
onTabl esareusedt
oimpr ove
perf
or manceoft heappl i
cati
onsinbackupandr ecov
eryprocess.Parti
ti
onTabl esarecreat
edonverylarge
databases.Par ti
tionTablesarecreatedbasedonkeycol
umn.Thi siscall
ed“ Part
it
ionKey”.
Oracl
ehav i
ng3t ypesofpar ti
ti
ons.
Rangepar titi
on
Listparti
ti
on
Hashpar ti
tion

RangePar t
it
ion:I
nt hispart
iti
onwear epart
it
ioni
ngtablesbasedonr angeofvalues.
Synt ax:
creat etabl
et abl
ename( col1datatype(si
ze),
col2dataty
pe(size)
,….)
partiti
onbyr ange(keycolname) (
par t
it
ionparti
ti
onnamev al
uesl essthan(
value)
,….
.,
part
it
ionpar
ti
ti
onname
valuesl essthan(maxv alue))
;

Ifwewanttovi
ewparti
cul
arport
ionthenwear eusingfoll
owingsy
ntax:
Syntax:
select*fr
om t
abl
enameparti
ti
on(par
tit
ionname1,part
it
ionname2,
……);

Eg:
sql
>createt
abl
etest
(snonumber
(10)
,namev archar2(
10),
salnumber(
10))
par
ti
ti
onbyrange(
sal
)(par
ti
ti
onp1val
ueslessthan(1000)
,par
tit
ionp2val
uesl
esst
han(
2000)
,par
ti
ti
onp3
val
ueslesst
han(
maxv al
ue))
;

MUARLISI
R 2015
127

Cl
assi
fi
cat
ion:
Publ
ic
Tabl
ecreated
Sql
>inserti
ntotestval
ues(
&no,„&name‟
,&sal
);
Sql
>select*from t
estpart
it
ion(
p1);
OUTPUT:
SNO NAME SAL
-
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
-
1 ABC 500

ListParti
ti
on:Or
acle9i
,intr
oducedl
i
stpar
ti
ti
oni
nthi
spar
ti
ti
onwear
epar
ti
ti
oni
ng
tablesbasedonli
stofvalues.

creat
et abl
etablename(col
1datatype(
size),col2dat
aty
pe(si
ze),….
.)
parti
ti
onbyl i
st(
keycolname)
(part
it
ion parti
ti
onname val
ues(value1, val
ue2,…),
………………………………….. part
it
ion
parti
ti
onnamev alues(
defaul
t)
);
NOTE:Gener all
y,i
fwewantt ocreateparti
ti
onbasedonchar acterdat
aty
pecol
umnthenwear
eusi
ng“List
Parti
ti
on”.

Sql>createtabletest(snonumber(10),namevarchar
2(10))par
ti
ti
onbyli
st(
name)(par
ti
ti
onp1
val
ues( „
Indi
a‟,
‟Nepal ‟)
, par
ti
ti
onp2v al
ues(„
us‟
,‟
uk‟,‟
canada‟)par
ti
ti
onp3values(
def
ault
));
sql>inserti
ntotestv alues(
&sno,
‟&name‟ )
;
sql>select*from test;
OUTPUT:
SNO NAME
--
--
--
--
---
--
---
--
--
--
-
AUS
JAPAN
INDIA

Sql
>select*from t
estpar
ti
ti
on(
p1)
;
OUTPUT:
SNO NAME
-
--
--
---
--
--
--
--
--
--
--
AUS
JAPAN

3.HASHPARTI TION:
In“HashPar t
it
ion”oracl
eserv
eronlycreatesparti
ti
onsbyusing“HashAl
gor
it
hm”
.
Syntax:
createtabl
etablename(col
1datat
ype(size),col
2datat
ype(
size)
,……)
parti
ti
onbyhash( keycol
name)par
tit
ionany number;

Eg:
MUARLISI
R 2015
128

Cl
assi
fi
cat
ion:
Publ
ic
Sql
>createtabl
et est(snonumber(10),
salnumber(10))par
ti
ti
onbyhash( sal)par
ti
ti
on5;
Tabl
ecr
eat
ed
Sql
>inserti
ntovaluest est(
&sno,&sal
);
I
fwewantt ov i
ewpar ti
ti
onsthenweareusing“user_t
ab_part
it
ions”dat
adi cti
onar
y.
Eg:
Sql
>descuser _
tab_ parti
ti
ons;
Sql
>selectpart
it
ion_ namef r
om user_
tab_
parti
ti
onswher etabl
e_name=‟TEST‟ ;

ENDOFSQL(
STRUCTUREDQUERYLANGUAGE(
SEQUEL)
)

ByDI
NESHLI
NGALA

MUARLISI
R 2015
129

Cl
assi
fi
cat
ion:
Publ
ic

You might also like