0% found this document useful (0 votes)
31 views

Cos 421 Note B

Uploaded by

Ezeuko Emmanuel
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)
31 views

Cos 421 Note B

Uploaded by

Ezeuko Emmanuel
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/ 51

Okor

onkwoM.
CCOS421Not
eBPage1of1
STRUCTUREDQUERRYLANGUAGE(
SQL)

HistoricalNote
Theor i
ginsofSQLcanbet racedtoanI BM researchpaperpubl i
shedin1974,tit
ledSEQUEL:A
StructuredEnglishQueryLanguage,byDonal dD.Chamber l
i
nandRay mondF.Boy ce.Raymond
Boy ce,whosadl ydi
edint hesamey ear,1974,wast hepersonwhosenamei senshr inedinBoyce-
CoddNor malForm( BCNF),descri
bedinChapt er7oft hetheorybook.Thi
spaperact ual
l
ysai d
nothingaboutdat abasemanagementbuti tassumedt heexi st
enceofrel
ati
on-l
iket hi
ngscalled
tablesanddef i
nedanot ati
onf orexpr
essingquer i
esont ablesinthedecl
arati
vemannert hatis
expect edforrel
ati
onaldatabases.

Apr ot oty pei mpl ement at i


onofSEQUEL, namedSEQUEL- XRM, waspr oducedi n1974–75.
Exper iencewi t
ht hi spr otot ypel edi n1976–77t oar ev i
sedv ersionoft hel anguage, SEQUEL/ 2,
subsequent lyr enamedSQLf orl egal r
easons.Wor kt henbeganonSy stem R, anot her,mor e
ambi tiouspr ot oty pe, i
mpl ement i
ngasubsetoft hatr ev i
sedv ersi on.
A si gni f i
cantai m ofSy stem R wast ogai nsayt hosepundi tswho wer escept icalaboutt he
possi bilityofpr ov idingar el ationalDBMSwi thper formancecompar abl et ot hatobt ainabl ewi th
conv ent ionaldat abaset echnol ogyatt het i
me,andi twaswi del ylaudedashav i
ngsucceededi n
thatai m.Sy stem Rbecameoper ationali n1977andwasi nst al ledatanumberofi nter nalsitesi n
IBM andataf ewsel ect edcust omersi tes.Exper ienceswi thSy stem Rr esul tedi nf urtherchanges
toSQLandsoonexpect at i
onswer ehi ght hatI BM woul dev entual lydev elopcommer cialSQL
product s—sohi ght hatonev endoror gani zat ion,nownamedOr acleCor por ation,beatI BM t oi tin
1979 wi tht he f irstr el ease ofORACLE.I BM’ s own f ir
stSQL pr oduct ,SQL/ DS f ort he VSE
env ironment ,appear edi n1981andi mpl ement ationsonot herpl atformsf olloweddur i
ngt he1980s.
Oneoft hesewasDB2f orOS/ MVSi n1983,andmuchl aterDB2becamet hegener icnamef oral l
ofI BM’ si mpl ement at ions.
Ahostofot herv endor sj oi nedt hegameov ert henextt wodecades, includi ng, etc.,Micr osoft( with
SQLSer ver,naught ilypr onounced“ sequelser v
er ”!),Sybase,I ngr es,andDi gitalEqui pmentCor p.,
(withRDB,now ownedbyOr acl e).Thosel astt wo,I ngresandRDB,or iginallyusedt heirown
l
anguages, bot hi nspi redbyCodd’ sr elational cal cul us,butl ateracqui r edanSQLi nter f
ace.
Thef irstedi ti
onoft hei nt er nat i
onal (ISO)st andar df orSQLappear edi n1987asar atif
icationof
onepr oduceday earear l
ierbyt heDat abaseCommi tteeX3H2oft heAmer icanNat i
onal Standar ds
Institut e( ANSI ) .Fur therdev elopmentoft hest andar dhast akenpl acesi ncet heni nISO—orr ather ,
undert heauspi cesofa“ joi ntt echni cal commi tt
ee” , JTC1, ofI SOandI EC, responsi blef oral l
i
nt ernat ional I
Tst andar ds.Theedi tionsar er ef erredt oasSQL: yy yy,wher ey y yyi sthey earof
publ icat ion.
Theso- call
ed“ ref er ent iali ntegr ity”f eatur e,suppor tingpr imar ykey sandf or eignkey s,appear edi n
SQL: 1989.SQL: 1992cont ainedsomanyaddi ti
onalf eaturest hati tslanguagehadbeenr eferredt o
att het imeasSQL/ 2.I n1996addi tionalf eat ur esknownasSQL/ PSM ( apr ogr ammi ngl anguage
forst or edpr ocedur esandf unct i
ons)andSQL/ CLI( a“ calll ev elint erface” )wer eadded.Att he
samet ime,t hecommi tteewaswor kingonf urtherext ensi onst ot hel anguage,r esul ti
ngi nt he
appear anceof“ SQL/ 3”asSQL:1999,whosemostsi gnifi
cantaddi t
ionwast heso- called“ object -
relational ”feat ur esuppor tinguserdef inedt y pes.Fur therr ev isionsappear edi n2003,2007,and
2011.Thatl astone, SQL: 2011( reference[ 15] ),isnot ablefori t smodi cum ofsuppor tfor“ tempor al
dat abase”management .
Manyoft headdi ti
onalf eat ur esappear i
ngi npost -1989edi tionsar especi fiedasopt ional ,meani ng
thatt heyar en’tr equi redf orani mpl ement ationt oqual i
fyasst andar d-conf or ming.
Hist or i
calnot esappear ingl ateri nt hi sbook,concer ni
ngspeci ficf eat uresofSQL,r efermost l
yt o
thepr e- 2000edi tionsoft heI SOSQLst andar d:1987, 1989, 1992, 1996, 1999, thoughi nconnect i
on
witht henot at i
onf orquer iescansomet imest akey our i
ghtbackt othe1974SEQUELpaper .

WhatI
sanSQLDat
abase?
AnSQLdat
abasei
sonewhosesy
mbol
sar
eor
gani
zedi
ntoacol
l
ect
ionoft
abl
es.
Okor
onkwoM.
CCOS421Not
eBPage2of2
SQLI saDat abaseLanguage
Thecommandsgi ventoaDBMSbyanappl icat
ionarewr i
tt
eni nt
hedat abasel anguageofthe
DBMS.Thet erm datasubl anguagei ssomet imesusedi nst
eadofdat abasel anguage.Thesub-
prefi
xreferst othef actthatapplicat
ionpr ogramsaresomet imeswritt
eni nsomemor egener
al-
purposeprogr ammi nglanguage( the“host”language),
inwhichthedatabasel anguagecommands
are embedded i n some pr escri
bed style.Somet i
mes the embedding stylei s such thatt
he
embeddedst atement sareunr ecognizedbyt hehostlanguagecompi l
erori nterpr
eter,andsome
specialprepr ocessoris used t or eplace the embedded statements by,f orexampl e,CALL
stat
ement sint hehostlanguage.

Whyt heconcer nedaboutSQL?


Untilrecentl
y,ifyouwer en'
tworki
ngonal argedat
abasesyst
em, y
ouprobablyhadonl
yapassing
knowledgeofSQL.Wi ththeadventofcl i
ent/
serv
erdevel
opmenttools(suchasVisualBasic,
VisualC++,ODBC,Bor land'
sDelphi,andPowersof
t'
sPowerBuil
der
)andthemov ementofseveral
l
argedat abases( Oracleand Sybase)t othePC plat
for
m,mostbusi nessappli
cat
ionsbeing
developedt odayr equir
eawor ki
ngknowl edgeofSQL.

WhatDoesanSQLDBMSDo?
I
nr esponsetorequest sfrom applicationpr ograms,anSQLDBMScan, forexampl
e,
o cr eat
eanddest r
oybaset ables
o Changesy stem secur i
tyset tings
o Adduserper mi ssionsondat abasesort ables
o t akenoteofintegrit
yrulesexpr essedasconst raint
s
o t akenoteofaut hori
sations( whoi sal l
owedt odowhat ,
towhat)
o updat evari
ables( honouringconst r
aintsandaut hori
sati
ons)
o pr ovi
deresulsofquer
t i
es
I
nt heremainingsectionsoft hischapt eryouwi l
lseeexampl esofhowanSQLDBMSdoest
hese
t
hings( vi
acommands—usual lycalledst atements—wr i
tteninSQL,ofcourse).

SQLi nAppl icati


onPr ogrammi ng
SQLwasor i
ginallymadeanANSIst andar di n1986.TheANSI1989st andar d(oft
encall
edSQL- 89)
defi
nest hreet ypesofi nterfacingtoSQLwi thinanappl icati
onpr ogram:
 Mo dul eLanguage-Usespr ocedureswi thinprograms.Thesepr ocedur escanbecal l
edbyt he
appl i
cat i
onpr ogram andcanr etur
nv aluest othepr ogram v i
apar amet erpassing.
 E mbeddedSQL- UsesSQLst at
ement sembeddedwi thact ualprogram code.Thi smet hodoften
requirest heuseofapr ecompi l
ertopr ocesst heSQLst atement s.Thest andarddefi
nes
statement sf orPascal ,FORTRAN, COBOL, andPL/ 1.
 Di rectInv ocat ion-
Leftupt ot heimpl ement er
.
Beforet heconceptofdy nami cSQLev olved, embeddedSQLwast hemostpopul arwayt ouseSQL
wit
hi napr ogram.EmbeddedSQL,whi chi sst illused,usesst aticSQL( t
heSQLst atementis
compi ledint otheappl i
cationandcannotbechangedatr untime).Thepr inci
pleismucht hesame
asacompi l
erv er susani nterpret
er.Theper formancef orthistypeofSQLi sgood;howev er
,iti
s
notflexibleandcannotal way smeett heneedsoft oday'schangi ngbusi nessenv i
ronment s.

TheANSI1992st andard(SQL-
92)ext endedthelanguageandbecameaninter
nati
onalst
andard.It
defi
nest hreelevelsofSQLcompl iance:ent
ry,i
ntermediat
e,andful
l
.Thenewfeatur
esint
roduced
i
ncludethef oll
owi ng:
 Co nnect i
onst odatabases
 Sc rol
lablecursor s
 Dy nami cSQL
 Ou terjoins
Dynami cSQLal lowsy outopreparetheSQLst atementatrunti
me.Alt
houghtheperf
ormancef or
Okor
onkwoM.
CCOS421Not
eBPage3of3
thistypeofSQLisnotasgoodasthatofembeddedSQL,itprovi
destheappl
i
cat
iondev eloper
(anduser)wit
hagreatdegr
eeoffl
exi
bil
i
ty.Acal
l-
lev
eli
nter
face,suchasODBCorSy base'sDB-
Librar
y,i
sanexampl
eofdynami
cSQL.

Call
-l
ev elint
erfacesshouldnotbeanewconceptt oappl i
cati
onprogr
ammer s.Whenusi ngODBC,
fori
nstance, yousimplyfil
lav ar
iabl
ewi t
hy ourSQLstatementandcallt
hef uncti
ont osendt he
SQLst atementt othedatabase.Errorsorresul
tscanber etur
nedtotheprogr am t
hrought heuse
ofotherf uncti
oncallsdesignedforthosepurposes.Resultsarer
etur
nedthroughapr ocessknown
asthebi ndingofv ar
iabl
es.

Cl
assi
fi
cati
onofSQLSt atement
s
Keywords/ Commands Function Remar ks
1 SELECT,FROM DataRetrieval(DR) Thisretr
ievedatafrom t
abl
esand
viewsofDBs
2 INSERT,UPDATE, DataMani pulati
on Thesear eusedt omanipul
ate
DELETE,MERGE (DM) existi
ngrecords.
3 CREATE, ALTER, DataDefinit
ion Theseset ,changesandremoves
DROP,RENAME (DD) tablestr
uctures.
TRUNCATE
4 COMMI T, ROLLBACK Transacti
on Managest hechangesmadebyDM.
SAVEPOI NT Control(
TC)
5 GRANT, REVOKE Datacontrol (
DC) Gi vesorremov esrightt
obothdbase
andst r
uctures.

Cr
eat
ingandDest
roy
ingBaseTabl
es

SQLCREATETABLE
Thecr eatet
ablestat
ementi susedt ocreateanewt able.TheCREATETABLEst atementdef
inesa
tabl
e.Thedef ini
ti
onmusti ncludei tsnameandt henamesandat t
ribut
esofi tscolumns.The
defi
niti
oncanincludeotherat t
ributesoft hetabl
e,suchasi t
spr
imar
ykey( orcheckconstr
aint
s).
Thisstatementcomesundert heDDLst atement .
Syntax:
SQL>Cr eat
et abletablename
(Column1dat at ype[defaultexp][
Constraint]
,
Column2dat atype[ defaul
texp][Constrai
nt ]
,
Column3dat atype[ defaul
texp][Constrai
nt ]
,
);

Tocreat
eanewt able,entert
hekey wor dscreatetabl
efoll
owedbyt hetabl
ename, f
ol l
owedbyan
openparent
hesi
s,f oll
owedbyt hefirstcol
umnname,f oll
owedbyt hedatat ypefort hatcol
umn,
fol
lowedbyanyopt i
onalconst rai
nts,andf oll
owedbyacl osingpar ent
hesis.Itisi mport
antt o
makesureyouuseanopenpar enthesisbeforethebeginningt
ableandacl osingparenthesi
safter
theendoft helastcol umndef i
nit
ion.Makesur ey ousepar ateeachcol umndef ini
ti
onwi t
ha
comma.ForOracleDBal l
SQLst atement sshouldendwi t
hasemi -colon";
".

Exampl
e:
SQL>Cr eatet ableempl
oyee(
Namev archar2( 15)
,
Ei
dnumber( 6),
Agenumber( 3),
Cityvar
char 2( 30),
Statevarchar2( 20)
);
Okor
onkwoM.
CCOS421Not
eBPage4of4

I
fyouwantt
oseet
hest
ruct
ureoft
het
abl
ethenuset
hef
oll
owi
ngcommandonSQLpr
ompt
.

SQL>DESCempl
oyee;

Theabovecommanddi splayst heentir


eattr
ibutenameswi tht
hei
rdatatypeandifconstr
aint
sare
i
mposedt hent hei
rdetailalso.
Youcanal socreat
eat ablef rom anexisti
ngt ablebycopy i
ngtheexi
sti
ngtabl
e'scolumns.Iti
s
i
mpor t
antt onotethatwhencr eatingatabl
eint hisway,thenewtabl
ewi l
lbepopulatedwit
hthe
recor
dsfrom theexisti
ngt able( basedontheSELECTSt atement)
.

Sy
ntax#1-Copy
ingal
lcol
umnsf
rom anot
hert
abl
e

SQL>CREATETABLEnew_tabl
e
AS(SELECT*FROM ol
d_t
able)
;

Exampl
e:
SQL>CREATETABLEper sons
AS(sel
ect*f
rom per
sons);

Thecommandwoul dcr
eateanewtablecall
edper
sonsthati
ncl
udedall
columnsfr
om t
heper
sons
table.
I
ft herewerer
ecordsintheol
dtabl
e,thenthenewtabl
ewouldalsocont
ainther
ecor
dssel
ect
ed
byt heSELECTstatement.

Sy
ntax#2-Copy
ingSel
ect
edcol
umnsf
rom anot
hert
abl
e

SQL>Cr eateTableTablename
(<columnname1>"col umnname2>)asselect
Statement ;
Where<columnnamel >,col
umnname2>ar ethenewcol
umnsi
nnewt
abl
ewi
thnewnamet
obe
associ
atedwiththev aluesret
urnedbyt hesubquer
y.

Exampl
e:
SQL>CreateTablePer
sons
(Per
son_i
d,name)
ASSELECT( P_I
d,Fi
rst
Name)f
rom per
sons;

Note:Creat
ingat
ablefr
om anothert
abl
ewi
thoutcopy
inganyv
aluesf
rom t
heol
dtabl
e:
Example:
SQL>CREATETABLEper sons
AS(select*fr
om per
sonswhere1=2);

SQLALTER-Mod ifyi
ngt heTabl eSt ructurewi thalterTabl eCommand
Aftercr eat
ingt hetableonemayhav eneedt ochanget het abl
eei
therbyaddi ngnewcol umnsorby
modi fyingtileexist
ingcol umns.
TheSQLALTERTABLEst at ementisthecommandt hatmakeschangest ot hedefinit
ionofanSQL
table.Tabl est r
ucturecanbechangedbyusi ngaltercommand.Wi ththi
scommandFi eldtypeor
proper tycanbechangedoranewf iel
dcanbeadded.
Toal terat able,t
het ablemustbei nyourschema, oryoumusthav ealt
ertablepriv
ilege.
Afterthet able(s)ar ecreat edandbegi nt obeused, r
equirementsareli
kelytooccurwhi chrequires
modi ficati
onsi nthest r
uct ur eofthetable,suchasaddingnewcol umnst othet abl
e, modif
yingand
existi
ngcol umn'sdef i
niti
onet c.Sot hesemodi fi
cati
onscanbeper formedusi ngtheALTERt able
DDLst atement .
UsingALTERTABLEst atement ,y
oucanmaket hefoll
owingmodi f
icati
ons:
Okor
onkwoM.
CCOS421Not
eBPage5of5
o Addacolumnt oat able.
o Changethedefinit
ionofanexi st
ingcol umni natable.
o Enabl
eordisableint egri
tyconstrai
nt.
o Speci
fyt
hedef aultv aluefortheexist
ingcol umns.
o Addordroponeormor ecolumnsto/f rom exi
sti
ngt abl
e.
o Changeanexistingcol umnf rom mandat or
ytooptionalorvi
cev
ersa.
o Enabl
eordisableint egri
tyconstrai
nts.
o Add/Modify/Del eteintegri
tyconstraintsassociat
edt o/fr
om t
hetabl
e.
o Speci
fyadefaultv al
uef orexisti
ngcolumn.

NOTE:TOALTERat abl
e,thetablemustbecontai
nediny
ourschemaoryoumusthav
eei
thert
he
ALTERobj
ectpr
ivi
l
egef orthetableorALTERanytabl
esyst
em pr
ivi
l
ege.

ADDI
NGNEW COLUMNS/CONSTRAI
NTSI
NEXI
STI
NGTABLE

Thesy
ntaxis:
ALTERTABLE<tablename>
ADD(column_
specifi
cationIconst
rai
n_speci
fi
cati
on,
..
..
col
umn_speci
fi
cat
ionI const
rai
n_speci
fi
cati
on);

Wheretabl
enamecorrespondstot henameoft het
abl
e,column_speci
fi
cationcor
respondst
othe
val
i
dspecifi
cati
onforacolumn( columnnameanddatatype)andconst
raintspeci
fi
cati
on
cor
respondstoval
i
dconst r
aintspecif
icat
ion.

Example:Toaddaddr
esscol
umni
ntot
heI
NSTRUCTORt
abl
ewi
thcol
umnwi
dth30anddat
aty
pe
varchar
2isshownbel
ow.

SQL>ALTERTABLEi
nst
ruct
or
ADD(addr
essVARCHAR2(
30)
);

I
nsteadofaddingcol
umnsonebyonewecanaddmult
ipl
ecolumnsi
nthet
abl
e.Toaddaddr
ess
andsalar
ycolumnsint
otheI
NSTRUCTORtabl
e,t
hest
atementis

SQL>ALTERTABLEi nst r
uct
or
ADD( addressVARCHAR2( 30),
Sal
aryNUMBER( 10,2))
;
Simil
arl
yyoucanaddconst r
aintst
ot heexi
sti
ngt able.Ify
ouf or
gettoaddpr
imarykeyconst
rai
nt
tothetabl
eatthet
imeofcr eati
on,youcanaddi tlaterusi
ngALTERTABLEst at
ement.Simil
arl
y
youcanaddotherconstr
aintssuchasf or
eignkey ,check,uni
queetc.

Now letussupposet hatnopri


marykeyconst r
aintexi
stsforINSTRUCTORt
abl
ebecausei
fit
exi
ststhenwecannotdef ineanew oneunlesswedr optheexist
ingoneweaddapri
marykey
const
raintwi
thinst
_idcolumnoftheI NSTRUCTORt abl
e,usingALTERTABLEstat
ementgi
ven
bel
ow.

SQL>ALTERTABLEinst
ruct
or
ADD(CONSTRAINTPK_ I
NSTRUCTORPRI
MARYKEY(I
NST_
ID)
);

Letusassumet hatnofor
eignkeyexist
sintheINSTRUCTORt abl
ewhi chr
efer
encesthe(dept_i
d)
pri
marykeyofDEPARTMENTt able.Soweaddaf or
eignkeyconstr
aintonthedept
_idcolumnof
theINSTRUCTORt abl
ewhichref
erstothedept_
idprimarykeycol
umnoft heDEPARTMENTt abl
e,
usingtheALTERTABLEcommandgi venbel
ow.

SQL>ALTERTABLEinstr
uct
or
ADD(CONSTRAINTFK_INSTRUCTORFOREI
GNKEY(
dept
_id)
Okor
onkwoM.
CCOS421Not
eBPage6of6
REFERENCESdepar
tment(
dept
_id)
);

Thefol
lowingpoint
sshoul
dbekepti
nmi
ndwhenaddi
ngnewcol
umns/const
rai
ntsi
ntot
he
exi
sti
ngtables.

o Youcanaddoneormor ethanonecol umnatt hesamet ime.


o Thereisnoneedofpar entheses;ify
ouaddi ngonlyasinglecolumnorconst rai
nt.
o Beforeaddi
ngapr i
mar ykeymakessur ethatnoduplicat
ev al
uesexistforacolumn( s)on
whichpri
marykeyi sappli
ed.
o Beforeaddi
ngaf orei
gnkey ,makesur ethatpri
mar ykeyconstr
aintmustexistinthe
ref
erri
ngtabl
e.
o Youmayaddacol umnatanyt i
mei fNOTNULLi snotspecifi
ed.Howev er,
youcanadda
newcolumnwi t
hNOTNULLonl yift
hetableisempt y.
o I
fat abl
econtai
nsr ecordsandy ouaddanewcol umn( s)tothi
stable,t
hent heini
ti
alval
ue
ofeachrowforthenewcol umni sNULL.

MODI
FYI
NGCOLUMNS!CONSTRAI
NTSI
NEXI
STI
NGTABLE

TheALTERTABLEst atemental
sooff
erstheabil
i
tytomodi
fycol
umns/const r
aint
sintheexi
sti
ng
tabl
ewi t
houti
mpactinganyotherdat
ainthetabl
e.Usi
ngALTERTABLEst at
ement,wecan
i
ncreaseordecreasethecolumnwidt
hs,changi
ngacolumnfrom mandat
orytoopti
onal(NOT
NULLt oNULL)andv i
cev er
sa.

Thesy
ntaxis:
ALTERTABLE<t abl
ename>
MODIFY(col
umn_ speci
fi
cat
ionIconst
rain_
specl
lcat
ion,

col
umn_specif
icati
onIconstr
ain_
specl
lcat
ion)
;

Toincr
easet
hewidt
hofnamecol
umni
ntheI
NSTRUCTORt
abl
efr
om 15t
o20,
uset
hef
oll
owi
ng
ALTERTABLEst
atement
.

SQL>Al
tert
abl
einst
ruct
or
MODIFY(
namev ar
char
2(20)
);

Oracl
edoesn'
tal
lowyout
odecreasethecol
umn'
swi dt
heveni
fallt
hecol
umnv
aluesar
eofv
ali
d
l
ength.Sot
oreducet
hewidt
hofthecolumn,
thev
aluesmustbesett
oNULL.

Youcanmodifyacolumnfrom NULLt
oNOTNULLconstrainti
fthet
abl
econtai
nsnorecor
dsin
thatcol
umn.However,
ift
hecolumncont
ainsv
aluesf
oreachrowofthetabl
eyoucannotmodi
fy
i
tf r
om NULLtoNOTNULL.

SQL>Al
tert
abl
einst
ruct
or
MODIFY(
namev ar
char
2(20)NOTNULL)
;

Youcanchanget
hedat
aty
peoft
hecol
umnsi
fcol
umncont
ainsNULLv
aluesf
orev
eryr
owoft
he
tabl
e.

SQL>Al
tert
abl
einst
ruct
or
MODIFY(
namechar(20)
);

DROPPI
NGCOLUMNS/
CONSTRAI
NTS

Youcannotonl
ymodifycol
umnsthatexi
sti
nyourt
ablesbuty
oucanal
sodropt
hem ent
ir
ely
.You
canal
soremovetheconst
rai
ntsf
rom t
hetabl
eusi
ngtheALTERTABLEstat
ement
.Whena
Okor
onkwoM.
CCOS421Not
eBPage7of7
const
rai
nti
sdr
opped,
anyassoci
atedi
ndexwi
tht
hatconst
rai
nti
sal
sodr
opped.

Thesy
ntaxfordr
oppi
ngacolumnis:
ALTERTABLE<tabl
ename>DROPCOLUMN<Col
umnname>;

Thi
ssy
ntaxi
sval
i
dify
ouwantt
odr
oponecol
umnatat
ime.

Todr
opt hePHONEcolumnfrom t
heINSTRUCTORtabl
e,t
heALTERTABLEst
atementi
s:
SQL>Altert
abl
einst
ruct
ordropcol
umnphone;

I
fauserwishest odropmulti
plecol
umnsusi
ngtheALTERTABLEst
atement
,thenuset
he
f
oll
owi
ngsy ntax.
ALTERTABLE<t abl
ename>
DROP( <columnname1>,<col
umnname2>);

Todr
opt hepostandt henamecol
umnf
rom t
heI
NSTRUCTORt
abl
e,t
heALTERTABLEst
atement
i
s
ALTERtableinstr
uctor
DROP(post,name) ;

Todropthepri
marykeyinst_
idfr
om t
hei
nst
ruct
ort
abl
e.Uset
hef
oll
owi
ngALTERTABLE
st
atement.
SQL>ALTERtableinstr
uct
or
DROPPRIMARYKEY;

I
fyouknowthenameoftheconstr
aint
,thenyoucandropallt
ypesofconst
rai
ntsl
i
kepr
imarykey
,
f
orei
gnkey,
checkconst
rai
ntset
c.Thesy nt
axforexecut
ingaboveusi
ngALTERTABLEstat
ement
i
s

ALTERTABLE<t
abl
ename>
DROPCONSTRAINT<const
rai
ntname>;

Supposewewanttodropt hefor
eignkeycol
umnDEPT_
IDwi
thconst
rai
ntnameFK_
INSTRUCTOR
thenuset
hefol
lowi
ngst at
ement.
SQL>ALTERtableinstr
uctor
DROPCONSTRAI NTFK_ INSTRUCTOR;

Thef
ollowingpoint
sshoul dbekepti nmindwhendr oppingthecol
umn/const raints:
o Youcannotdr opallthecolumnsi natable.
o Youcannotdr opacol umnsf rom tableswhoseowneri sSYS.
o Youcannotdr opapar ent,keycolumn( primarykey)unl
essyoudropthefor eignkeythat
ref
erencesit
.Todot his,CASCADEkey wordisused.
SQL>al t
ertabledepar tmentDROPPRI MARYKEYCASCADE;
o Youcanenabl eordisabl ethekeyconst r
aint
sinsituat
ionsl
ikewhenloadingl argeamount
ofdataint
oat able,performingbat choperat
ionsthatmakemassivechangest oat abl
e,
migrati
ngtheorganizat i
on'
sl egacydata.

Todi
sableconstr
aint
:
SQL>AlterTABLEi
nst
ruct
orDi
sabl
eConst
rai
ntPK_
INSTRUCTOR;

Toenabl
econst
rai
nt,
SQL>Alt
erTABLEi
nst
ruct
orEnabl
eConst
rai
ntPK_
INSTRUCTOR;

I
nst
eadofdroppi
ngacolumn,youcanmakethecol
umnunusedanddropitl
ateron,
Itt
husmakes
t
heresponset
imefast
erthani
fyourex
ecut
edtheDROPclause.Af
teracol
umnhasbeenmarked
Okor
onkwoM.
CCOS421Not
eBPage8of8
asunused,
youhavenoaccesst
othatcol
umn.Theunusedcol
umnswil
lnotber
etri
evedwith
SELECT*quer
y.TheSETUNUSEDinformati
oni
sstor
edinUSER_UNUSED_COL_TABSdict
ionar
y
vi
ew.

SQL>al
tert
abl
einst
ruct
orSETUNUSEDCOLUMNphone;

SQLVI
EW
AVI
EW asweknowni sav irt
ualt able,throughwhi chasel ectiveporti
onoft hedatafrom oneor
mor
etablescanbeseen.Vi ewshav et hefollowingpr operti
es/characteri
sti
cs:
o Viewsdonotcont aindat aoft heirown.
o Viewsar eusedt orest r
ictaccesst othedat abaseort ohi dedatacompl exi
ty.
o AVi ewi sst oredasaSELECTst atementi nthedat abase.
o DMLoper at
ionsonav i
ewsuchasI NSERT, UPDATE, DELETEaf f
ectsthedataintheori
ginal
tableuponwhi chthev i
ewi sbased.
o Av iewcont ainsrowsandcol umns, j
ustlikear ealtable.
o Thef i
eldsi naVi ewar ef i
eldsf rom oneormor erealtablesinthedatabase.
o Av iewi saspeci fi
crepr esentationofdat af rom oneormor etables.
o Thet ablesreferredint hev i
ewsar eknownasBaset ables.
o Creat ingav i
ewdoesnott akeanyst oragespaceasonl ythequeryisstoredinthedat
a
dictionar yandt heact ualdat aisnotst oredany wher e.

UsesofViews
Therearemanyr easonsf orusingv i
ewsi nappli
cationssuchas:
o Reducingcompl exit
y
o Incr
easingSecur ity-sensiti
veinf
ormationcanbeexcl udedfr
om av i
ew
o Renami ngt ablecol umns-bygi vi
ngthedi f
ferentnamest ocolumnswhi l
ecreat
ingvi
ews.
o Representingasubsetoft hedatacontainedi nat able.
o Simplif
icati
onbyj oiningmul t
ipl
etablesintoasi nglev i
rt
ualt
able.
o StorageSpaceeconomy ;thedatabasecont ainsonlyt hedef
init
ionofav i
ew,notacopyof
allt
hedat ai tpresents.
o Givi
ngdi ff
er entuser sdif
ferentvi
ewscr eatedf r
om t hesamebaset able.

Cr
eat
ingViews
Tocr
eateav i
ew,youmustmeett hefol
lowingr equirements:
 Tocr eateaviewinyourschema, youmusthav etheCREATEVI EW pr i
vil
ege.
 Tocr eateaviewinanotheruser'
sschema, youmusthav etheCREATEANYVI EW system
pr
ivi
l
ege.Youcanacqui rethesepriv
ilegesexpl i
cit
lyorthr
oughar ole.
 Theowneroft hevi
ew( whetheri
tisy ouoranot heruser)musthav ebeenexpl i
cit
lygranted
pr
ivi
l
egest oaccessall
objectsrefer
encedi nthev i
ewdefini
tion.
o Theownercannothav eobtainedt hesepr i
vil
egesthroughr oles.
 Thef uncti
onalit
yofthev i
ewdependsont heprivi
legesofthev i
ewowner .
o Forexampl e,
iftheowneroft hev iewhasonl ytheINSERTpr ivil
egeforEMPt able,
thentheviewcanbeusedonl ytoi nsertnewr owsintotheEMPt abl
e,nottoSELECT,
UPDATE, orDELETEr ows.

Sy
ntax:
CREATE[ORREPLACE]VI EW <v
iew_name>
AS
SELECT<column_l
ist
>
FROM <t
able_name>[WHEREcondi t
ion]
[
WI THCHECKOPTI ON][
CONSTRAI NTconst
rai
n_name]
[
WI THREADONLY] ;

I
ntheSy
ntax,
View_
namespeci
fi
est
henameoft
hev
iewandmustf
oll
owt
her
ulesf
ori
dent
if
ier
s.
Okor
onkwoM.
CCOS421Not
eBPage9of9
Column_ l
istspeci
fi
esthenameofthecol
umnst obeusedi nvi
ew.Ifthecol
umn_li
stopti
onisnot
specif
ied,thentheview i
screat
edwitht
hesamecol umnsasspeci f
iedinthesel
ect_
statement
.
Select
_statementspeci
fi
estheSELECTSt
atementthatdef
inesavi
ew.

Theviewmayusethedat acontai
nedi
not herviewsandt abl
es.
WITH CHECKOPTI ON forcesthedat
amodi f
icati
onstatementstofulf
il
lthecri
ter
iagi
veninthe
SELECTstat
ementdefiningthevi
ew.I
talsoensur est
hatt hedat
aisvisi
bleaf
tert
hemodifi
cati
ons
aremadepermanent.
WITHREADONLYr estricttheDMLoperat
ionst obeperformedonthev i
ew.

Examples:
Consi
dertheEMPLOYEESt
abl
eandcr
eat
eaVi
ewf
ort
he'
EGBE'
;cannotaccesst
heSal
aryofal
l
theemployees.

SQL>DESCEMPLOYEES;
SQL>CREATEORREPLACEVI EW EGBE
2ASSELECTEID, NAMEFROM EMPLOYEES;
OnExecut
ionthevi
ewwi t
hName' EGBE'i
scr
eated.Onceyoucreateaviewitisassumedt obea
Tabl
e.Youcannowperformthevari
ousDMLoper at
ionsontheView.Butmakesur eifyouimpose
theCHECKOPTIONS,t
heny oucannotper
for
m anyoperati
on.Remembert hati
twillal
socopythe
Recor
dscontai
nedint
hebasetable.

ToDi
spl
ayal
lther
ecor
dsi
nthev
iew.

SQL>SELECT*FROM EGBE;

Afterexecut
ionthi
scommandwil
ldi
spl
ayal
ltherecor
dsofEMPtableaswhenviewi
scr
eat
edal
l
therecordsareaut
omati
cal
l
ycopi
edint
otheview.I
twil
ldi
spl
ayal
ltherecor
ds.

ReadOnlyOpti
on
I
fyouusereadonlyopt
ionintheviewduringcr
eati
on,
theny oucannotper
for
m anyDMLoperati
on
onthev
iew.Ify
out r
ytodothisthenerrormessagewi
llencount
er.WITHREADONLYr est
ri
ctthe
DMLoperati
onstobeperfor
medont heview

Consi
dertheEMPLOYEEStableandcreat
eav i
ewfort
he'
EGBEDEEP'
;shecannotaccesst
he
Sal
aryofall
theempl
oyees.Usetheconst
rai
nt'WI
THREADONLY.

SQL>cr
eat
evi
ewEGBEdeep

2assel
ectei
d,namef
rom empl
oyeeswi
thr
eadonl
y;

Af
terexecut
ionav
iewwiththename' EGBEdeep'
will
becreat
ed.I
nthevi
ewbecauset
heopt
ion
WITHREADONLYi suseditrest
ri
ctsanyDMLoper at
ionst
obeexecut
ed.

Modify
ingVi ews
Youcanuset heORREPLACEopt i
ontomodi f
ytheview.I
fthevi
ewexist
sitwi l
lber
eplacedwith
thenew defini
ti
onoranewv iew wi
llbecreat
ed.WecanuseCr eateorReplaceopt
iontocreate
viewsi
nsteadofdr oppi
ngthev i
ewandr ecr
eati
ngit
.Withthi
sopti
onthepri
vil
egesgr
antedont he
viewar
epr eserved,
butthedependentst
oredprogr
amsandv iewbecomeinv
alid.

Thev i
ewwi l
lbecomei nv
ali
dwhenev ert
hebasetableisal
ter
ed.Wecanrecompi
leav i
ew usi
ng
theAlterview stat
ement,butoracl
eautomati
cal
lyrecompi
lesthevi
ew oncei
tisaccessed.On
recompil
ing,thedependentobj
ectsbecomei
nvali
d.

Rest
ri
cti
onsonDMLSt
atement
s
Okor
onkwoM.
CCOS421Not
eBPage10of10
Therearecertainrulesthathavetobefollowedt operformt heDMLoper ati
ons.Theyar e:
o Youcannoti nserttherowsint
ov i
ewi fthebaset ablehascer tai
ncol umnswi t
hNOTNULL
constraintthatdoesnotappeari ntheview.
o Ifaviewi sdef i
nedbyaquer ythatcontainsSETorDI STINCToper ators,aGROUPBYcl ause,
oragr oupf unction,t
henrowscannotbei nser
tedi nt
o, updat
edin, ordeletedfr
om thebase
tabl
esusi ngt hev i
ew.
o Ifaviewi sdef i
nedwi t
hWI THCHECKOPTI ON,ar owcannotbei nsertedintoorupdatedin,
thebaset abl
e( usi
ngtheview),i
fthev i
ewcannotsel ecttherowf r
om t hebasetable.
o Ifvi
ewcont ainsWI THREADONLYConst rai
nttheny oucannotper form anyDMLoper ations.

RenamingCol
umns
Viewscanbeusedt
orenamethecol
umnswit
houtaf
fect
ingthebaset
ablespr
ovi
dedthatthe
numberofcol
umnsinaviewmustmatcht
henumberofcol
umnsspecif
iedint
hesel
ectstatement
.

Cr
eat
eav
iewEGBEf
rom t
het
abl
eempl
oyeeswi
thdi
ff
erentcol
umnnames,

SQL>CREATEORREPLACEVIEW EGBE
2(ENO,ENAME)
3ASSELECTEID,NAMEFROM EMPLOYEES;

Af
terexecut
iont
hev
iewEGBEwi
l
lbecr
eat
edwi
tht
hedi
ff
erentcol
umnnames

TheSELECTSt at
ement
Themostcommonlyusedstat
ementi nSQLi stheSELECTstatement
.TheStatementret
ri
eves
dat
afrom t
hedat
abaseandr
eturnsthedat
at otheuser.TheEMPLOYEEtabl
eexampleil
l
ustrat
es
aty
pical
exampl
eofaSELECTstatementsi
tuati
on.

Gener alRul esofSy ntax


Syntaxi nSQLi squi teflexible,althought her ear er ul
est of ol
lowasi nanypr ogr ammi nglanguage.
Asimpl equer yi l
lustratest hebasi csy ntaxofanSQLsel ectst atement .Paycl oseat t
ent i
ontothe
case, spacing, andl ogi cal separat ionoft hecomponent sofeachquer ybySQLkey wor ds.
SELECTNAME, STARTTERM, …, ENDTERM
FROM EMPLOYEE
WHERENAME=' OKORONKWO' ;
Inthisexampl eev erythingi scapi tal ized,buti tdoesn' thav et obe.Thepr ecedingquer ywouldwor k
j
ustaswel lifi
twer ewr i
ttenl i
ket hi s:
selectname, startterm, endt er m
fr
om empl oyee
wher ename=' OKORONKWO' ;
Noticet hatOKORONKWOappear sincapi tal letter
si nbot hexampl es.Althoughact ual SQL
statement sar enotcasesensi t
iv e,r eferencest odat ainadat abasear e.Forinst ance, many
compani esst oret heirdat ai nupper case.I nt hepr ecedi ngexampl e,assumet hatt hecol umnname
storesi t
scont entsi nupper case.Ther efor e, aquer ysear chingf or'Okoronkwo' i
nt henamecol umn
woul dnotf indanydat ator eturn.Checky ouri mplement ationand/ orcompanypol ici
esf orany
caser equi r
ement s.
NOTE:Commandsi nSQLar enotcasesensi ti
ve.
Takeanot herl ookatt hesampl equer y.I
st her esomet hingmagi cal i
nt hespaci ng?Agai nthe
answeri sno.Thef ollowingcodewoul dwor kaswel l
:
selectname, startterm, endt ermf rom empl oy eewher ename=' OKORONKWO' ;
Howev er,somer egar df orspaci ngandcapi tali
zationmakesy ourst atementsmucheasi ertoread.
Ital
somakesy ourst atement smucheasi ert omai ntainwhent heybecomeapar tofy ourproj
ect.
Anot herimpor tantf eaturef orOr acl eDBi s; semi colon( ;
)t hesampl equer yist hesemi colonatthe
Okor
onkwoM.
CCOS421Not
eBPage11of11
endoftheexpressi
on.Thispunctuationmarktell
sthecommand- l
ineSQLprogram t
hatyourquery
i
scompl et
e.
Ift
hemagi ci
sn'ti
nthecapit
ali
zationortheformat ,
thenjustwhi
chelementsar
eimpor t
ant
?The
answeriskey
wor ds,
orthewor dsinSQLt hatarereserv
edasapar tofsy
ntax.(
Dependingont he
SQLstatement,akeywordcanbeei theramandat oryel
ementofthestat
ementoroptional
.)The
keywor
dsintheexampl eabovear e:
 SE LECT
 F ROM
 WHE RE

TheBuildi
ngBl ocksofDat aRetr
iev al
:SELECTandFROM
AsyourexperiencewithSQLgr ows, youwillnoti
cet hatyouaret ypi
ngthewor dsSELECTand
FROM mor ethananyot herwordsint heSQLv ocabul ar
y.Theyar en'
tasglamor ousasCREATEor
asrut
hlessasDROP, buttheyareindispensabletoanyconv er
sationyouhopet ohav ewitht
he
computerconcerningdataretr
ieval.Andisn'
tdatar etri
evalthereasonthatyouent eredmountai
ns
ofi
nformationintoyourveryexpensi v
edatabasei nthef i
rstpl
ace?
Thi
sdiscussionstart
swi thSELECTbecausemostofy ourstatementswillal
sost artwit
hSELECT:
SYNTAX:
SELECT<COLUMNNAMES>

TheSELECTdoesnotwor kal
one.Ifyout
ypedjustSELECTint
oyoursystem, y
oumi ghtgetthe
fol
lowingresponse:
SQL>SELECT;
Yougetaner rordispl
aylike:
SELECT
*
ERRORatl i
ne1:
ORA- 00936: missi
ngexpression
Theast eri
skundert heof f
endingl
ineindi
cat
eswher eOracl
e7thi
nkstheoffenseoccurred.The
err
ormessaget ell
sy outhatsomet hi
ngismissi
ng.Thatsomethi
ngistheFROM clause:
SYNTAX:
FROM <TABLE>
Together,thestatement sSELECTandFROM begi ntounlockt
hepowerbehi ndyourdatabase.

NOTE:key wor
dsclauses.Atthi
spointyoumaybewonder i
ngwhatthedif
ferenceisbetweena
keyword,astatement,andaclause.SQLkeywordsrefertoindi
vi
dualSQLel ements,suchas
SELECTandFROM.A cl ausei
sapar tofanSQLst atement;forexample,SELECTcol umn1,
column2,..
.isacl ause.YoucombineSQLcl ausestof or
m acompl et
eSQLst atement.For
example,y
oucancombi neaSELECTclauseandaFROM clausetowri
teanSQLst at
ement.

NOTE:Eachimplementat
ionofSQLhasauni quewayofi ndi
cati
ngerrors.MicrosoftQuery,f
or
example,
saysi
tcan'
tshowt hequery,l
eav
ingyoutof
indtheprobl
em.Bor l
and'sInter
basepopsup
adial
ogboxwiththeer
ror.PersonalOr
acl
e7,t
heengineusedinthepr
ecedi ngexampl e,
givesyou
anerrornumber(soyoucanl ookupt hedetai
l
edexplanati
oni nyourmanual s)andashor t
expl
anati
onoft
heprobl
em.

Terminati
nganSQLSt at
ement
I
nsomei mpl
ement at
ionsofSQL,t
hesemi col
on(;)att
heendofthestat
ementtel
lstheinter
pret
er
thatyouarefi
nishedwr i
ti
ngthequery.Forexample,Oracl
e'
sSQL*PLUSwon'texecut
et hequery
unti
li
tfindsasemicolon(orasl
ash).Ontheotherhand,someimpl
ementat
ionsofSQLdonotuse
Okor
onkwoM.
CCOS421Not
eBPage12of12
t
hesemicol
onasat ermi
nator.Forexampl
e,Micr
osof
tQueryandBorl
and'
sISQLdon'
trequi
rea
t
ermi
nat
or,becausey
ourqueryisty
pedinanedi
tboxandexecut
edwhenyoupushabut
ton.

Changingt heOrderoftheCol umns


Tospecif ytheorderoft
hecol umns,youcouldty pesomet hingl
ike:
SQL>SELECTpay ee,remarks,amount,check#f rom checks;
Not i
cethateachcol umnnamei sl
istedintheSELECTcl ause.Theorderinwhi
cht hecolumnsare
l
istedist heorderinwhicht heywil
lappearint heout put.Noti
ceboththecommast hatseparat
e
thecolumnnamesandt hespacebet weenthef inalcol
umnnameandt hesubsequentclause(i
n
thi
scaseFROM) .Theout putwouldlookliket
his:

7r
owssel
ect
ed.

Anotherwayt owrit
ethesamest at
ementf oll
ows.
SELECTpay ee,r
emar ks,
amount, check#
FROM checks;
Noti
cet hatt
heFROM cl ausehasbeencar riedovert
othesecondl
ine.Thi
sconvent
ionisamatt
er
ofpersonaltast
ewhenwr i
ti
ngSQLcode.
Theout putisidenti
calbecauseonl ythef ormatofthestat
ementchanged.Now thatyouhave
est
ablishedcontrolovertheorderofthecol umns,youwil
lbeabl
et ospeci
fywhichcolumnsyou
wanttosee.

Sel
ecti
ngDif
fer
entTables
Supposey
ouhadat abl
ecall
edDEPOSI
TSwi
tht
hisst
ruct
ure:

Wit
hasi ngl
echangey ouhaveanewdat asour
ce.
YouwouldsimplychangetheFROM clausetot
hedesi
redt
abl
eandt
ypet
hef
oll
owi
ngst
atement
:
SQL>select*fr
om deposi
ts
Theresulti
s

Quer
ieswi
thDi
sti
nct
ion
Okor
onkwoM.
CCOS421Not
eBPage13of13
I
fyoul ookatt heor i
ginal
table,CHECKS, youseet hatsomeoft hedatar
epeats.Forexample,
if
youlookedatt heAMOUNTcol umnusi ng:
SQL>sel ectamountf rom checks;
youwoul dsee
AMOUNT
--
----
---
150
245. 34
200. 32
98
150
25
25.1
Noti
cet hatt heamount150i srepeated.Whati fyouwant edtoseehowmaydi f
fer
entamounts
wereint hiscol umn?Tr ythis:
SQL>sel ectDISTINCTamountf rom checks;
Theresul twoul dbe
AMOUNT
--
----
---
25
25. 1
98
150
200. 32
245. 34
6rowssel ected.
Noti
cet hatonl ysi xrowsaresel ect
ed.Becausey ouspecifi
edDISTINCT,onl
yonei nst
anceofthe
dupl
icateddat aisshown, thismeanst hatonelessr owisretur
ned.ALLi
sakey wor dt
hatis
i
mpliedint hebasi cSELECTst atement .Youalmostnev erseeALLbecauseSELECT<Tabl e>and
SELECTALL<Tabl e>havet hesamer esult
.

Exercise
1.Dot hef ollowingstatementsreturnthesameordi f
fer
entoutput:
SELECT*FROM CHECKS;
select*f rom checks; ?
2.Thef ol
lowi ngqueri
esdonotwor k.Whynot ?
a.Select*
b.Select*f rom checks
c.Selectamountnamepay eeFROM checks;
3.Whi choft hef ol
lowingSQLst atement swil
lwork?
a.select*
from checks;
b.select*f rom checks;
c.select*f rom checks
/
4.Usingt heCHECKSt ablefr
om earli
ertoday,wri
teaquerytoretur
njustthechecknumber
sand
theremar ks.
5.Rewr itet hequer yfrom exer
cise1sot hatt
heremarkswil
lappearast hef
ir
stcolumni
nyour
queryr esul t
s.
6.Usingt heCHECKSt able,
writ
eaquer ytoret
urnal
ltheuni
quer emarks.
Okor
onkwoM.
CCOS421Not
eBPage14of14
Cl
ausesi
nSQL
Object
ives
Bytheendoft hedayy ouwi l
lunder standandbeabl etouset
hefol
l
owingcl
ausesy
oucanuse
withSel
ectst atement :
 WHE RE
 STARTI NGWI TH
 ORDE RBY
 GROUPBY
 HAVI NG
Thegeneral syntaxf oraSELECTst at ementi s:
SYNTAX:
SELECT[ DISTI NCT| ALL]{*
| {[schema. ]
{tabl e| vi
ew| snapshot
}.
*
| expr}[[ AS]c_ alias]...}
FROM [ schema. ]{t
able| vi
ew| snapshot}.
..
[WHEREcondi ti
on]
[GROUPBYexpr[ ,expr]...[HAVI NGconditi
on]]
[{
UNI ON| UNI ONALL| INTERSECT| MINUS}SELECTcommand]
[ORDERBY{ expr|posit
ion}[ ASC| DESC]
[,{expr|positi
on}[ASC| DESC] ].
..
]
NOTE:Thepr ecedingsy ntaxwi l
lgener al
lyworkwi t
hanySQLengi
ne,
butyoumayfind
somesl i
ghtv ari
at i
ons.

Don'tworr
yaboutt heexactsyntax-i
tvari
essli
ghtl
yfrom implementat
iontoi mpl
ement at
ion
anyway.I
nstead,f
ocusontherelati
onshi
ps.Atthetopofthi
sst at
ementi sSELECT,SELECTi s
fol
l
owedbyFROM, whi
chshoul
dappearwi thev
erySELECTstatementyoutyped.WHERE, GROUP
BY,HAVING,andORDER BYal lf ol
low.Eachclausepl
aysani mportantpartinselect
ingand
manipul
ati
ngdata.

TheWHERECl ause
UsingjustSELECTandFROM, youar eli
mi tedt oreturningev er
yr owinat able.WithWHEREiny our
vocabulary,youcanbemor eselecti
ve.Tof indal lt
hechecksy ouwr otewithav alueofmorethan
100dol l
ars,writethi
s:
SQL>SELECT*
2FROM CHECKS
3WHEREAMOUNT>100;
TheWHEREcl ausereturnstheinstancesi nt hetablet hatmeett herequir
edcondi ti
on:
WHEREcanal sosolveot herpopularpuz zles.Gi venat abl
eofnamesandl ocati
ons,youcanask
thatpopularquest i
on,Wher e'
sWal do?
SQL>SELECTLOCATI ONAS" WHERE' SWALDO? "
2FROM PUZZLE
3WHERENAME=' WALDO' ;
OUTPUT:
WHERE' SWALDO?
--
---
--
--
---
--
GARAGE
Thisquer yshowst hatthecolumnusedi nt hecondi t
ionoft heWHEREst atementdoesnothav eto
bement ionedi ntheSELECTcl ause.Int hisexampl ey ouselectedthelocationcolumnbutused
WHEREont hename, whi chisperfectl
ylegal .Alsonot icetheASont heSELECTl ine.ASi
san
optionalassignmentoper ator,
assigningt heal iasWHERE' SWALDO?t oLOCATI ON.Youmi ght
neverseet heASagai n,becausei tinvol
v esext r
at yping.Inmosti mplement ati
onsofSQLy oucan
Okor
onkwoM.
CCOS421Not
eBPage15of15
t
ype
SQL>SELECTLOCATION"WHERE'SWALDO? "
2FROM PUZZLE
3WHERENAME=' WALDO'
;
andgetthesameresul
tast
heprev
iousquerywi
thoutusingAS:
OUTPUT:
WHERE' SWALDO?
-
--
---
--
--
--
--
GARAGE
Aft
erSELECTandFROM, WHERE,i
sthethi
rdmostfrequentl
yusedSQLt
erm.

TheSTARTINGWI THCl ause


STARTINGWITHi sanadditi
ontot heWHEREcl
auset
hatwor
ksexact
lyl
i
keLI
KE(
<exp>%)
.
Comparetheresul
tsofthefoll
owingquer
y:
SELECTPAYEE, AMOUNT, REMARKS
FROM CHECKS
WHEREPAYEELI KE('
Ca%')
;

and
SELECTPAYEE, AMOUNT, REMARKS
FROM CHECKS
WHEREPAYEESTARTI NGWI TH('
Ca'
);
Ther
esultsar
eidenti
cal.Youcanevenuset
hem t
oget
her
,asshownher
e:
SELECTPAYEE, AMOUNT, REMARKS
FROM CHECKS
WHEREPAYEESTARTI NGWI TH('
Ca'
)
OR
REMARKSLI KE'G%';

WARNI NG:STARTINGWITHisacommonfeat
ureofmanyi
mpl
ement
ati
onsofSQL.Check
youri
mplementat
ionbef
orey
ougrowfondofi
t.

TheORDERBYCl ause
SELECTFROM gi vesy oual i
sting,andunl essy ouhav edefinedapr i
marykey ,yourquerycomes
outint heordert her owswer eenter ed.Considert hef ol
lowingquer yonCHECKSt able:
SELECT*FROM CHECKS;
Theor deroft heout putisexact l
ythesameor derast heorderinwhi chthedat awasent ered.
TheORDERBYcl ausegi v esyouawayofor deringy ourresults.Forexampl e,toorderthe
precedinglisti
ngbychecknumber ,y ouwoul duset hefoll
owi ngORDERBYcl ause:
SQL>SELECT*
2FROM CHECKS
3ORDERBYCHECK#;
Nowt hedatai sorder edthewayy ouwanti t,nott hewayi nwhi chitwasent ered.Asthefoll
owing
exampl eshows, ORDERr equiresBY; BYisnotopt ionalthef oll
owingquery.
SQL>SELECT*FROM CHECKSORDERCHECK#;
Displaythef oll
owi nger r
orf l
ag:
SELECT*FROM CHECKSORDERCHECK#
*
ERRORatl i
ne1:
ORA-00924: missingBYkey wor d
Ifyouwantt oli
stt hedat ainr everseor der,
wi t
ht hehi ghestnumberorl etterf i
rst
?Thef ol
lowing
Okor
onkwoM.
CCOS421Not
eBPage16of16
querygener atesal istofPAYEEst hatstarsatt heendoft heal
phabet:
SQL>SELECT*
2FROM CHECKS
3ORDERBYPAYEEDESC;
TheDESCatt heendoft heORDERBYcl auseor derstheli
sti
ndescendingorderinsteadoft he
default(ascendi ng)order .
Thisquer yalsoshowst hatt heexpr essi
onusedaf tertheORDERBYclausedoesnothav etobein
theSELECTst at ement .Althoughy ouselectedonl yPAYEEandAMOUNT, youwer est i
llableto
orderthel i
stbyCHECK#.
Youcanal souseORDERBYonmor ethanonef i
eld.ToorderCHECKSbyPAYEEandREMARKS,
youwoul dquer yasf oll
ows:
SQL>SELECT*
2FROM CHECKS
3ORDERBYPAYEE, REMARKS;
Addingt hefieldREMARKSt otheORDERBYcl auseput st
heent
ri
esinalphabeticalorderaccordi
ng
toREMARKS.Doest heor derofmul ti
plecolumnsi ntheORDERBYclausemakeadi ff
erence?Try
thesamequer yagai nbutr ev ersePAYEEandREMARKS:
SQL>SELECT*
2FROM CHECKS
3ORDERBYREMARKS, PAYEE;
Ther esult
sar ecompl etelydi ff
er ent.Here'
showt ol i
stonecol
umninalphabeticalorderandl i
st
thesecondcol umni nrev erseal phabet i
calorder:
SQL>SELECT*
2FROM CHECKS
3ORDERBYPAYEEASC, REMARKSDESC;
I
nt hi
sexampl ePAYEEi ssor tedal phabet i
call
y,andREMARKSappear sindescendingor der
.

TIP:Ifyouknowthatacol
umnyouwantt
oorderyourresul
tsbyist
hefi
rstcol
umni
na
table,t
henyoucantypeORDERBY1inpl
aceofspell
i
ngoutt hecol
umnname.Seet
he
foll
owingexample.
SQL>SELECT*
2FROM CHECKS
3ORDERBY1;

Thi
sresul
tisi
dent
ical
tot
her
esul
tpr
oducedbyt
heSELECTst
atementt
haty
ouusedear
li
er:
SELECT*FROM CHECKSORDERBYCHECK#;

TheGROUPBYCl ause
TheSQLGROUPBYcl auseisusedalongwitht
heSQLaggregatefunct
ionsandspecif
iesthe
groupswher
esel
ectedrowsareplaced.Whenoneormoreaggregatefunct
ionsarepresent
edi
n
theSQLSELECTcolumnli
st,t
heSQLGROUPBYcl ausecal
cul
atesasummar yval
ueforeach
group.

Sy
ntax:
SQL>SELECTcol umn_name,
aggregate_
funct
ion(
col
umn_
name)
FROM t
able_name
WHEREcol umn_nameoperat
orvalue
GROUPBYcol umn_ name;

GROUPBYi saninval
uableSQLclauseforor
ganizi
ngandper f
ormi
ngoperati
onsoninf
ormation
aboutsever
aldi
ff
erenti
temsyouwanttoaggr egat
e.Forinst
ance,
whatifyouwant
edtoget
i
nformati
onaboutemployeeat
tendanceinseveral
dif
ferentt
imeperi
odstodocomparisonsand
Okor
onkwoM.
CCOS421Not
eBPage17of17
char
ti
ng?

Exampl
es:
a.Tofi
ndoutt
heTot
alsal
aryofal
ltheDepar
tment
s.

SQL>SELECTDEPTNO,
SUM (
SAL)"
DEPARTEMENTSALARY"
2FROM EMPGROUPBYDEPTNO;

DEPTNO DEPARTEMENTSALARY

10 8750
20 10875
30 9400

b.Tol
i
stt
heav
eragesal
aryofeachj
obi
ntheEMPt
abl
e

SQL)SELECTJOB,
AVG(
SAL)
FROM EMPGROUPBYJOB;

JOBS SAL
ANALYST 3000
CLERK 1037.
5
MANAGER 2758.
33333
PRESIDENT 5000
SALESMAN 1400

Tof
indoutt
hej
obsofi
ndi
vi
dual
depar
tment
s

SQL>SELECTJOB,
COUNT( JOB)“
TOTALJOBS”FROM EMP
GROUPBYDEPTNO, JOB;

TOTALJOBS JOB

1 CLERK
1 MANAGER
1 PRESIDENT
2 ANALYST
2 CLERK
1 MANAGER
1 CLERK
1 MANAGER
4 SALESMAN

I
fyouwant
edtofi
ndthet
otal
amountofmoneyspentf
rom t
heCHECKSt
abl
e,y
ouwoul
dwr
it
e:
SELECTSUM(AMOUNT)
FROM CHECKS;

OUTPUT
SUM
==========
1159.
87
Thi
sstatementret
urnst
hesum oft
hecol
umnAMOUNT.
Okor
onkwoM.
CCOS421Not
eBPage18of18
I
fyouwant
edtofindouthowmuchyouhav
espentoneachPAYEE?SQLhel
psyouwit
hthe
GROUPBYclausetofi
ndoutwhom y
ouhavepai
dandhowmuch,youwoul
dqueryl
i
kethis:
SELECTPAYEE, SUM(AMOUNT)
FROM CHECKS
GROUPBYPAYEE;

I
fyouhadtri
edthi
squerywi
thonl
ytheFROM CHECKSt
hatf
oll
ows,
her
e'swhaty
ouwoul
dsee:
SELECTPAYEE,SUM(
AMOUNT)
FROM CHECKS;

DynamicSQLErr
or
-
SQLer r
orcode=-104
-
inval
i
dcolumnrefer
ence

SQLiscomplai
ningaboutthecombinat
ionofthenor
mal col
umnandt heaggr
egatefuncti
on.Thi
s
condi
ti
onrequi
restheGROUPBYcl ause.GROUPBYr unstheaggregat
efunct
iondescri
bedinthe
SELECTstat
ementf oreachgr
oupi
ngoft hecol
umnthatfoll
owstheGROUPBYcl ause.

Whatwouldhappeni
fyoutri
edt
ogroupbymorethanonecol
umn?Tr
ythi
s:
SELECTPAYEE,SUM(AMOUNT),COUNT(
PAYEE)
FROM CHECKS
GROUPBYPAYEE, REMARKS;

Thenextexamplefi
ndsthel
argestandsmall
estamounts,gr
oupedbyREMARKS:
SELECTMI N(
AMOUNT) ,MAX( AMOUNT)
FROM CHECKS
GROUPBYREMARKS;
I
fy out
rytoincl
udei
nthesel
ectstatementacolumnthathassever
aldi
ff
erentv
alueswi
thi
nthe
groupf
ormedbyGROUPBY:
SELECTPAYEE, MAX(
AMOUNT) ,MIN(
AMOUNT)
FROM CHECKS
GROUPBYREMARKS;

Youwill
gett his:
DynamicSQLEr r
or
-SQLerr
orcode=- 104
-i
nval
i
dcol umnr efer
ence
Thi
squer
ytr
iestogr oupCHECKSbyREMARK.Whent
hequer
yfi
ndst
wor
ecor
dswi
tht
hesame
REMARKbutdif
ferentPAYEEs,itt
hrowsaner
ror
.

Therul
eis,Don'
tusetheSELECTstat
ementoncol
umnsthathav
emulti
plev
aluesfortheGROUP
BYcolumn.Therever
seisnottr
ue.YoucanuseGROUPBYoncolumnsnotmentionedint
he
SELECTstatement
.
Forexample:
SELECTPAYEE, COUNT(AMOUNT)
FROM CHECKS
GROUPBYPAYEE, AMOUNT;

Thisqueryshowshowmanychecksy ouhadwr
it
tenf
orident
ical
amount
stothesamePAYEE.It
s
realpurposei
stoshowthatyoucanuseAMOUNTintheGROUPBYclause,
eventhoughi
tisnot
ment i
onedintheSELECTcl
ause.
Okor
onkwoM.
CCOS421Not
eBPage19of19

TrymovingAMOUNToutoft heGROUPBYcl auseandintot


heSELECTclause,l
i
kethi
s:
SELECTPAYEE, AMOUNT, COUNT(AMOUNT)
FROM CHECKS
GROUPBYPAYEE;
YougetaDy nami cSQLError
-
SQLer r
orcode=- 104
-
inv
alidcolumnr efer
ence
SQLcannotrunthequer y,whi chmakessensei fyoupl
aythepar
tofSQLf oramoment.Sayy
ou
hadtogroupthefoll
owingl i
nes:
SELECTPAYEE, AMOUNT, REMARKS
FROM CHECKS
WHEREPAYEE=' Cash';
Ift
heuseraskedy outoout putal l
thr
eecolumnsandgr oupbyPAYEEonly,wher
ewouldyouput
theuni
queremarks?Remembery ouhaveonlyonerowpergroupwheny ouuseGROUPBY.SQL
can'
tdotwothingsatonce, soitcomplai
ns:Error#31:
Can'tdot
wot hi
ngsatonce.

TheHAVI NGClause
How cany ouqualifythedat
ausedinyourGROUP BY cl
ause?HAVING enabl
esyoutouse
aggregat
efuncti
onsinacompari
sonst
atement
,pr
ovi
dingforaggr
egat
efuncti
onswhatWHERE
prov
idesfori
ndiv
idualr
ows.

Uset
het abl
eORGCHARTandtr
ythi
s:
SELECT*FROM ORGCHART;

Ify
ouwant edtogrouptheoutputi
ntodi
visi
onsandshowtheaver
agesal
aryineachdi
visi
on,
you
wouldtype:
SELECTTEAM, AVG(SALARY)
FROM ORGCHART
GROUPBYTEAM;
Thefol
lowingstat
ementqualif
iest
hisquerytor
etur
nonl
ythosedepar
tmentswit
haverage
sal
ari
esunder38000:
SELECTTEAM, AVG(SALARY)
FROM ORGCHART
WHEREAVG( SALARY)<38000
GROUPBYTEAM;

DynamicSQLEr ror
-
SQLer rorcode=-104
-
Inval
i
daggr egateref
erence
Thi
serroroccurr
edbecauseWHEREdoesnotwor kwithaggregat
efuncti
ons.Tomaket
hisquer
y
work,
youneedsomet hingnew:theHAVINGcl
ause.I
fyoutypethefol
lowingquer
y,y
ougetwhat
youaskfor:
SELECTTEAM, AVG(SALARY)
FROM ORGCHART
GROUPBYTEAM
HAVINGAVG( SALARY)<38000;

DoesHAVINGworkwit
hnonaggr
egat
eexpr
essi
ons?Tr
ythi
s:
SELECTTEAM,AVG(
SALARY)
FROM ORGCHART
Okor
onkwoM.
CCOS421Not
eBPage20of20
GROUPBYTEAM
HAVINGSALARY<38000;
Whyisthi
sresul
tdif
fer
entfr
om thelastquery
?
TheHAVINGAVG( SALARY)<38000cl auseeval
uat
edeachgroupingandret
urnedonl
ythosewi
th
anaver
agesalar
yofunder38000,j
ustwhaty ouexpected.
HAVI
NGSALARY<38000, ontheotherhand,wil
lproduceadi
ff
erentout
come.

Takeont herol
eoftheSQLengi neagai
n.Iftheuserasksy outoevaluat
eandreturngr
oupsof
divi
sionswher eSALARY<38000,y ouwouldexami neeachgr oupandr ej
ectt
hosewherean
i
ndividualSALARYi sgreaterthan38000.Ineachdi vi
sion,youwoul dfi
ndatleastonesalar
y
greaterthan38000.Theref
ore,youwouldrejectal
l
.Whaty oureal
lyaskedwasSelectal
lgr
oups
wherenoi ndi
vi
dualmakesmor et han38000.Don'tyouj usthat
ei twhenthecomputerdoes
exactlywhatyoutel
li
tto?

WARNI NG:Somei mpl


ementat
ionsofSQLretur
nanerrorifyouuseanyt
hingot
hert
hanan
aggregat
efuncti
oninaHAVINGclause.Don'
tbetonusingtheprev
iousexampl
eunti
lyou
checktheimplement
ati
onofthepart
icul
arSQLyouuse.

Canyouusemor ethanonecondi ti
oniny ourHAVI
NGclause?Tr
ythi
s:
SELECTTEAM, AVG( SICKLEAVE),AVG(ANNUALLEAVE)
FROM ORGCHART
GROUPBYTEAM
HAVINGAVG( SICKLEAVE) >25AND
AVG(ANNUALLEAVE) <20;
Thefol
lowi
ngtableisgroupedbyTEAM.I tshowsal
lthet
eamswithSICKLEAVEav
eragesabov
e
25daysandANNUALLEAVEav eragesbelow20days.

Youcanalsouseanaggregat
efunct
ioni
ntheHAVINGclauset
hatwasnoti
ntheSELECT
st
atement.Forexampl
e:
SELECTTEAM, AVG(SI
CKLEAVE),
AVG(ANNUALLEAVE)
FROM ORGCHART
GROUPBYTEAM
HAVINGCOUNT( TEAM)>1;

Thi
squeryret
ur nst henumberofTEAMswi thmorethanonemember .COUNT(TEAM)i
snotused
i
ntheSELECTst atementbutstil
lfunct
ionsasexpect
edintheHAVI NGclause.
Theot
herlogical operat
orsallworkwellwit
hint
heHAVI NGclause.Considert
his:
SELECTTEAM, MIN(SALARY),MAX(SALARY)
FROM ORGCHART
GROUPBYTEAM
HAVINGAVG( SALARY)>37000
OR
MIN(SALARY)>32000;

Theoperat
orI
NalsoworksinaHAVINGcl
ause,
asdemonst
rat
edher
e:
SELECTTEAM,AVG(SALARY)
FROM ORGCHART
GROUPBYTEAM
HAVINGTEAM IN('
CS',
'
ST')
;
Okor
onkwoM.
CCOS421Not
eBPage21of21
Combi
ningCl
auses
Nothi
ngexi
stsi
navacuum,sothi
ssect
iontakesyouthroughsomecomposi
teexampl
est
hat
demonst
rat
ehowcombinat
ionsofcl
ausesperfor
mt ogether
.

Exampl e
Findal lthecheckswr i
tt
enf orCashandGasi ntheCHECKSt ableandordert
hem byREMARKS.
SELECTPAYEE, REMARKS
FROM CHECKS
WHEREPAYEE=' Cash'
ORREMARKSLI KE'Ga%'
ORDERBYREMARKS;
Not etheuseofLI KEt ofi
ndt heREMARKSt hatstart
edwit
hGa.Wi t
htheuseofOR, datawas
returnedi ftheWHEREcl ausemetei theroneofthetwocondit
ions.
Whati fy ouaskedf orthesamei nf
ormat i
onandgr oupi
tbyPAYEE?Thequer ywouldlook
somet hingl ikethi
s:
SELECTPAYEE, REMARKS
FROM CHECKS
WHEREPAYEE=' Cash'
ORREMARKSLI KE'Ga%'
GROUPBYPAYEE
ORDERBYREMARKS;
Thisquer ywoul dnotwor kbecausetheSQLengi newouldnotknowwhatt odowiththeremarks.
Remembert hatwhatevercolumnsy ouputintheSELECTclausemustalsobeintheGROUPBY
clause--unlessy oudon'tspecif
yanycol umnsintheSELECTclause.

Exampl e2
Usingthetabl
eORGCHART, fi
ndthesal
aryofever
yonewit
hlessthan25day
sofsickl
eav
e.Or
der
theresult
sbyNAME.
SELECTNAME, SALARY
FROM ORGCHART
WHERESI CKLEAVE<25
ORDERBYNAME;
Thisqueryisst
raight
forwardandenabl
esyoutouseyournew-f
oundski
ll
swithWHEREand
ORDERBY.

Exampl e3
Again,usingORGCHART, di
splayTEAM,AVG(SALARY),
AVG(
SICKLEAVE)
,and
AVG( ANNUALLEAVE)oneacht eam:
SELECTTEAM,
AVG( SALARY),
AVG( SI
CKLEAVE),
AVG( ANNUALLEAVE)
FROM ORGCHART
GROUPBYTEAM;
Aninteresti
ngv ar
iat
ionont
hisqueryf
oll
ows.Seeify
oucanf
igur
eoutwhathappened:
SELECTTEAM,
AVG( SALARY),
AVG( SI
CKLEAVE),
AVG( ANNUALLEAVE)
FROM ORGCHART
GROUPBYTEAM
Okor
onkwoM.
CCOS421Not
eBPage22of22
ORDERBYNAME;

Asi
mplerquer
yusi
ngORDERBYmi
ghtof
feracl
ue:
SELECTNAME,TEAM
FROM ORGCHART
ORDERBYNAME, TEAM;

NAME TEAM
==========================
ADAMS ST
FURY BM
MERRICK ST
MEZA BM
PRECOURT CS
RICHARDSON MKT
STOKES MKT
WILKES MKT
WhentheSQLengi negotar oundtoor deri
ngt heresul
tsofthequery,i
tusedtheNAMEcol umn
(r
emember,itisperfectl
ylegalt
ouseacol umnnotspeci f
iedintheSELECTstatement)
,ignor
ed
dupl
i
cateTEAM ent ri
es,andcameupwi t
ht heorderST,BM, CS,andMKT.Includi
ngTEAM inthe
ORDERBYcl auseisunnecessar y
,becausey ouhaveuniquev al
uesint
heNAMEcol umn.Youcan
gett
hesamer esul
tbyt ypi
ngthi
sst at
ement :
SELECTNAME, TEAM
FROM ORGCHART
ORDERBYNAME;

Whi
l
eyouarelooki
ngatvar
iat
ions,
don'
tfor
gety
oucanal
sor
ever
set
heor
der
:
SELECTNAME, TEAM
FROM ORGCHART
ORDERBYNAMEDESC;

Exampl e4:
Isitpossibl
et ouseev ery
thi
ngyouhavel
ear
nedinonequery?I
tis,butt
heresul
tswi l
lbe
convolutedbecauseinmanyway syouar
eworki
ngwithappl
esandor angesoraggregat
esand
nonaggr egates.Forexample,WHEREandORDERBYar eusual
lyfoundinqueri
esthatacton
singl
er ows,suchast his:
SELECT*
FROM ORGCHART
ORDERBYNAMEDESC;

GROUPBYandHAVINGarenor
mall
yseeni
nthecompanyofaggr
egat
es:
SELECTPAYEE,
SUM(AMOUNT)TOTAL,
COUNT(PAYEE)NUMBER_WRI
TTEN
FROM CHECKS
GROUPBYPAYEE
HAVINGSUM(AMOUNT)>50;

Youhaveseenthatcombi
ningt
heset
wogr
oupsofcl
ausescanhav
eunexpect
edr
esul
ts,
incl
udi
ng
thef
oll
owing:
SELECTPAYEE,
Okor
onkwoM.
CCOS421Not
eBPage23of23
SUM(AMOUNT)TOTAL,
COUNT( PAYEE)NUMBER_WRITTEN
FROM CHECKS
WHEREAMOUNT>=100
GROUPBYPAYEE
HAVINGSUM( AMOUNT)>50;
Comparethesetworesul
tset
sandexaminet
her
awdat
a:
SELECTPAYEE, AMOUNT
FROM CHECKS
ORDERBYPAYEE;

Youseehowt heWHEREcl ausefil


teredoutal
l thechecksl essthan100dol lar
sbef or
et heGROUP
BYwasper f
ormedont hequer y.Wear enottr
y i
ngt otelly
ounott omi xthesegr oups-
-youmay
havear equi
rementt hatthissortofconst r
uct
ionwi l
l meet.Howev er,youshouldnotcasual l
ymix
aggregateandnon- aggregatefunctions.Thepreviousexampl eshav ebeent abl
eswi t
honl ya
handfulofrows.(Otherwise,youwoul dneedacar ttocarrythisbook.)Intherealworldy ouwil
lbe
workingwiththousandsandt housands( orbi
l
lionsandbi ll
ions)ofrows, andthesubtlechanges
causedbymi xingthesecl ausesmi ghtnotbesoappar ent.

Exer
cises
1.Whi chclauseworksjustli
keLI KE(<exp>%)?
2.Whati st
hefuncti
onoft heGROUPBYcl ause,andwhatotherclausedoesitactl
i
ke?
3.Wi l
lthisSELECTwor k?
SQL>SELECTNAME, AVG( SALARY) ,
DEPARTMENT
FROM PAY_ TBL
WHEREDEPARTMENT=' ACCOUNTI NG'
ORDERBYNAME
GROUPBYDEPARTMENT, SALARY;
4.Whenusi ngtheHAVINGcl ause, doyoualway shavetouseaGROUPBYal so?
5.Cany ouuseORDERBYonacol umnt hati
snotoneoft hecol umnsintheSELECT
statement ?
6.Usingt heORGCHARTt ablefrom theprecedingexamples,
findouthowmanypeopl eon
eacht eam have30ormor edaysofsi ckleave.
7.Usingt heCHECKSt able,writ
eaSELECTt hatwillr
etur
nthef oll
owing:

Expr
essi
ons,
Condi
ti
ons,
andOper
ator
s
Object
ives
I
nt heprevi
oussect ionon“ TheSELECTSt atement ,
"y ouusedSELECTandFROM t omani
pul
ate
datainint
eresti
ng( anduseful)ways.Herey oulearnmor eaboutSELECTandFROM andexpand
thebasicquerywithsomenewt ermstogowi t
hquer y,tabl
e,androw,aswellasanewcl
auseand
agroupofhandyi temscalledoperat
ors.
 Kn owwhatanexpr essi
oni sandhowtousei t
 Kn owwhatacondi ti
onisandhowt ousei t
 Bef amil
iarwiththebasicusesoftheWHEREcl ause
 Bea bletousear it
hmetic,compari
son,character,l
ogical,
andsetoperat
ors
 Ha veawor ki
ngknowl edgeofsomemi scell
aneousoper ator
s

NOTE:WeusedOr acl
e'
sPersonal
Oracl
e7togenerat
etheexamples.Ot
herimpl
ementationsof
SQLmaydi f
fersli
ghtl
yinthewayinwhi
chcommandsar eenter
edoroutputi
sdispl
ayed,butthe
resul
tsar
ebasicall
ythesameforall
impl
ementat
ionsthatconf
ormtotheANSIstandard.
Okor
onkwoM.
CCOS421Not
eBPage24of24

Expressions
Anexpr essionr eturnsav al
ue.Expressiontypesareverybr
oad, cov
eri
ngdiff
erentdatat y
pessuch
asSt ri
ng,Numer i
c,andBool ean.Inf act,prett
ymuchany thingfoll
owingacl ause( SELECTor
FROM,f orexampl e)i sanexpr ession.Int hefoll
owingexampl eamountisanexpr essionthat
ret
urnst hev aluecont ainedintheamountcol umn.
SELECTamountFROM checks;
I
nt hefollowingst atementNAME, ADDRESS, PHONEandADDRESSBOOKar eexpr essi
ons:
SELECTNAME, ADDRESS, PHONE
FROM ADDRESSBOOK;
Now, exami net hefoll
owi ngexpression:
WHERENAME=' BROWN'
I
tcont ai
nsacondi t
ion,NAME=' BROWN' ,
whi chi
sanexampleofaBool eanexpression.NAME=
'
BROWN' wil
l beeitherTRUEorFALSE, dependingonthecondit
ion.

Conditions
Ify
ouev erwanttof indapar t
iculari
tem orgr
oupofi t
emsi nyourdatabase,youneedoneormor e
conditi
ons.Conditionsar econtainedintheWHEREcl ause.Intheprecedi
ngexampl e,t
hecondition
i
s:NAME=' BROWN'
Tofindev eryoneiny ourorganizati
onwhowor kedmor ethan100hour slastmont h,yourcondit
ion
wouldbe: NUMBEROFHOURS>100
Conditi
onsenabl ey out omakesel ecti
vequeri
es.I nthei
rmostcommonf or
m, conditi
onscompr ise
avariable,aconstant ,andacompar isonoperator.Inthefi
rstexamplethevariableisNAME, the
constantis'BROWN' ,andthecompar i
sonoperatoris=.Inthesecondexampl et hevari
ableis
NUMBEROFHOURS, theconstantis100,andthecompar i
sonoper at
oris>.Youneedt oknow
abouttwomor eelement sbef
or eyoucanwr i
tecondi ti
onalqueri
es:theWHEREcl auseand
operators.

TheWHERECl ause
ThesyntaxoftheWHEREclauseis
WHERE<SEARCHCONDI TION>
TheWHERE, si
mplycausesyourquer
iest
obemoresel
ecti
ve.Wit
houtt
heWHEREcl
ause,t
he
mostusefult
hingyoucoul
ddowi t
haqueryi
sdi
spl
ayallr
ecordsi
nthesel
ect
edt
abl
e(s)
.For
example:
SQL>SELECT*FROM BIKES;
l
istsal
lrowsofdatai
nthetabl
eBIKES.
NAME FRAMESI
ZE COMPOSI
TION MI
LESRI
DDENTYPE
-
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
---
--
--
--
--
-----
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
TREK2300 22.
5 CARBONFI
BER 3500RACI
NG
BURLEY 22 STEEL 2000TANDEM
GI
ANT 19 STEEL 1500COMMUTER
FUJI 20 STEEL 500TOURI
NG
SPECI
ALI
ZED 16 STEEL 100MOUNTAI
N
CANNONDALE 22.
5 ALUMI
NUM 3000RACI
NG
6rowsselected.
I
fyouwant edapar t
icul
arbike,y
oucoul
dty
pe
SQL>SELECT*
FROM BIKES
WHERENAME=' BURLEY';
whichwouldy i
eldonlyonerecord:
NAME FRAMESI ZE COMPOSI TI
ON MI
LESRI
DDENTYPE
Okor
onkwoM.
CCOS421Not
eBPage25of25
BURLEY 22 STEEL 2000TANDEM
Thi
ssi
mpleexampl
eshowshowy
oucanplaceacondi
ti
ononthedat
athaty
ouwantt
oret
ri
eve.

Operators
Operatorsar
et heel
ementsyouuseinsideanexpressi
ontoart
icul
atehowyouwantspeci
fi
ed
condit
ionstoretr
ievedat
a.Oper
ator
sf all
int
osixgroups:
ari
thmeti
c,compar
ison,
char
acter
,logi
cal
,
set,
andmi scell
aneous.

Arit
hmet icOper ators
Thear i
thmet icoper at
orsareplus(+),minus( -),
divide( /
),multi
ply(*),andmodul o(%).Thefirst
fouraresel f
-explanatory.Moduloretur
nst hei nt
egerr emainderofadi vi
sion.Herearetwo
exampl es:
5%2=1
6%2=0
Themodul ooper atordoesnotwor kwi t
hdat atypesthathav edeci mals,suchasReal orNumber .
Ifyouplacesev eraloftheseari
thmeticoper atorsinanexpr essionwi thoutanyparentheses,the
operatorsarer esolvedinthisorder:mult
ipli
cat i
on,divisi
on,modul o,addi t
ion,
andsubt r
acti
on.For
exampl e,t
heexpr essi
on
2*6+9/ 3 equal
s 12+3=15
Howev er,theexpr ession
2*( 6+9)/3 equal
s 2*15/3=10
Wat chwher ey ouputt hoseparentheses!Somet i
mest heexpressiondoesexact lywhaty outell
it
todo, r
athert hanwhaty ouwantittodo.
Thef ol
lowingsect i
onsexami nethearit
hmet i
coper at
or sinsomedet ailandgiveyouachancet o
writesomequer i
es.

Plus(+)
Youcanuset heplussi gni nsev eralways.Ty pethef ol
l
owi ngstat
ementt odisplaythePRICEtable:
SQL>SELECT*FROM PRI CE;
I
TEM WHOLESALE
-
--
----
--
--
--
---
---
--
---
TOMATOES .
34
POTATOES .51
BANANAS .67
Nowt ype:
SQL>SELECTI TEM, WHOLESALE, WHOLESALE+0. 15
FROM PRI CE;
Herethe+adds15cent st oeachpr i
cetopr oducet hef ol
lowing:
I
TEM WHOLESALE WHOLESALE+0. 15
TOMATOES .34 .49
POTATOES .
51 .66
BANANAS .67 .82
Whati sthislastcolumnwi ththeunat t
ractiv
ecol umnheadi ngWHOLESALE+0. 15?It
'snotinthe
ori
ginaltable.(
Remember ,y
ouused*i nt heSELECTcl ause,whichcausesal lthecolumnstobe
shown.)SQLal l
owsy out ocr eateav i
rt
ualorder i
v edcol umnbycombi ningormodi fyi
ngexisti
ng
columns.
WHOLESALE+0. 15i snotaper manentpar tofit.I
nf act,thecolumnheadingi ssounat t
ract
ivethat
youshoul ddosomet hingabouti t
.
Typethef oll
owing:
SELECTI TEM, WHOLESALE, (WHOLESALE+0. 15)RETAIL
FROM PRI CE;
Okor
onkwoM.
CCOS421Not
eBPage26of26
Here'
st her esul
t:
I
TEM WHOLESALE RETAIL
TOMATOES .34 .49
POTATOES .51 .66
BANANAS .67 .82
Thisiswonder f
ul!Notonl ycany oucreatenewcol umns,butyoucanal
sor enamethem onthefl
y.
Youcanr enameanyoft hecol umnsusi ngthesyntaxcolumn_nameali
as(notethespacebetween
column_ nameandal i
as).
NOTE:Somei mplement ationsofSQLuset hesyntax<columnname=al i
as>.Theprecedi
ng
examplewoul dbewr it
tenasf ol
l
ows:
SELECTI TEM =PRODUCE,
WHOLESALE,
WHOLESALE+0. 25=RETAI L,
FROM PRI CE;
Checky ouri mplementationf ort
heexactsy ntax.

Youmi ghtbewonder i
ngwhatuseal iasingi
sifyouar enotusi
ngcommand- li
neSQL.Fai renough.
Havey ouev erwonder edhowr eportbuilder
swor k?Someday ,whenyouareaskedt owritearepor
t
generator,y ou'll
remembert hisandnotspendweeksr ei
nvent
ingwhatDr.CoddandI BM have
wrought.
Insomei mpl ement ati
onsofSQL, theplussigndoesdoubl edutyasacharacteroperat
or.You'l
l
seethatsi del ater.
Minus( -)
Minusal sohast wouses.Fi r
st, i
tcanchanget hesi gnofanumber .Youcanuset hetabl
eHI LOW
todemonst rat ethisfunction.
SELECT*FROM HI LOW;
STATE HI GHTEMP LOWTEMP
CA -
50 120
FL 20 110
LA 15 99
ND -70 101
NE -
60 100
Forexampl e, here'
sawayt omani pulatethedat
a:
SELECTSTATE, -HIGHTEMPLOWS, -
LOWTEMPHI GHS
FROM HI LOW;
STATE LOWS HI GHS
CA 50 -120
FL -20 -110
LA -
15 -99
ND 70 -101
NE 60 -100
Thesecond( andobv ious)useoft hemi nussignist osubtr
actonecolumnfrom another.For
example:
SELECTSTATE,
2HI GHTEMPLOWS,
3LOWTEMPHI GHS,
4( LOWTEMP-HI GHTEMP)DI FFERENCE
5FROM HI LOW;

STATE LOWSHI
GHSDI
FFERENCE
CA -
50 120 170
Okor
onkwoM.
CCOS421Not
eBPage27of27
FL 20 110 90
LA 15 99 84
ND -
70 101 171
NE -
60 100 160
Noticetheuseofal i
asest ofixthedatathatwasenteredincorr
ectl
y.Thi
sremedyismer el
ya
temporarypatch,though, andnotaper manentfi
x.Youshoul dseetoitt
hatthedat
ai scor
rect
ed
andent er
edcorrectl
yi nthefuture.
Thisquerynotonl yfixed(atl
eastvisual
ly)t
heincorr
ectdatabutalsocreat
edanewcol umn
contai
ningthedi f
ferencebetweent hehighsandlowsofeachst ate.
Ifyouaccident
allyuset hemi nussignonacharacterfi
eld,yougetsomethi
ngliket
his:
SELECT- STATEFROM HI LOW;

ERROR:
ORA-01722:i
nval
i
dnumber
norowsselect
ed
Theexacter
rormessagevar
ieswi
thi
mpl
ement
ati
on,
butt
her
esul
tist
hesame.

Div
ide(/)
Thediv
isi
onoper
atorhasonl
yoneobv
iousmeani
ng.Usi
ngt
het
abl
ePRI
CE,
typet
hef
oll
owi
ng:
SELECT*FROM PRI
CE;
I
TEM WHOLESALE
-
--
--
--
--
--
--
---
--
--
--
-
TOMATOES .
34
POTATOES .
51
BANANAS .
67
Youcanshowt
heef
fect
sofat
wo-
for
-onesal
ebyt
ypi
ngt
henextst
atement
:
SELECTI
TEM,
WHOLESALE,
(WHOLESALE/
2)SALEPRI
CE
FROM PRI
CE;
I
TEM WHOLESALESALEPRI
CE
TOMATOES .
34 .
17
POTATOES .
51 .
255
BANANAS .
67 .
335
Theuseofdi
vi
sioni
nthepr
ecedi
ngSELECTst
atementi
sst
rai
ght
for
war
d

Mult
ipl
y(*)
Themulti
pli
cati
onoperat
orisalsost
rai
ghtfor
ward.Agai
n, usi
ngthePRI
CEt abl
e,t
ypethef
oll
owi
ng:
Thequerybelowchangesthetabl
etoref
lectanacross-
the-boar
d10percentdi
scount
:
SELECTI
TEM,
WHOLESALE,
WHOLESALE*0.
9NEWPRI
CE
FROM PRI
CE;

I
TEM WHOLESALENEWPRI
CE
TOMATOES .
34 .
306
POTATOES .
51 .
459
BANANAS .
67 .
603
Theseoper
ator
senabl
eyout
oper
for
m power
ful
cal
cul
ati
onsi
naSELECTst
atement
.

Modul
o(%)
Themodul
ooperat
orr
etur
nsthei
ntegerr
emai
nderoft
hedi
vi
sionoper
ati
on.Usi
ngt
het
abl
e
REMAI
NS,typet
hefol
l
owing:
SELECT*FROM REMAI
NS;
Okor
onkwoM.
CCOS421Not
eBPage28of28
NUMERATOR DENOMI
NATOR
10 5
8 3
23 9
40 17
Youcanal
socreat
eanewcol
umn,
REMAI
NDER,
tohol
dthev
aluesofNUMERATOR%
DENOMINATOR:

SELECTNUMERATOR,
DENOMI
NATOR,
NUMERATOR%DENOMI
NATORREMAI
NDER
FROM REMAI
NS;

NUMERATORDENOMI
NATORREMAI
NDER
10 5 0
8 3 2
23 9 5
Someimplementati
onsofSQLimpl
ementmodul
oasaf unct
ioncal
ledMOD
Thefol
l
owingstatementpr
oducesr
esul
tst
hatar
eident
icalt
otheresul
tsi
nthepr
ecedi
ng
st
atement
:
SELECTNUMERATOR,
DENOMI
NATOR,
MOD(
NUMERATOR,
DENOMI
NATOR)REMAI
NDER
FROM REMAI
NS;

Precedence
Hereweexami net heuseofpr
ecedenceinaSELECTstat
ement
.Usi
ngt
hedat
abasePRECEDENCE,
ty
pet hef ol
l
owi ng:
SELECT*FROM PRECEDENCE;
N1 N2 N3 N4
1 2 3 4
13 24 35 46
9 3 23 5
Uset hefoll
owingcodesegmentt otestpr
ecedence:
SELECT
2N1+N2* N3/ N4,
3( N1+N2) *N3/N4,
4N1+( N2*N3) /
N4
5FROM PRECEDENCE;

N1+N2* N3/N4 (N1+N2)*N3/N4 N1+(N2* N3)/


N4
2.5 2.25 2.5
31.26087 28.152174 31.26087
22.8 55.2 22.
8
93 975 93
Not
icethatthefi
rstandl
astcolumnsareidenti
cal
.Ifyouaddedaf our
thcol
umnN1+N2*(
N3/
N4)
,
i
tsval
ueswoul dalsobei
denticalt
othoseofthecurrentfi
rstandlastcol
umns.

ComparisonOperators
Comparisonoperat
orscompar eexpr
essi
onsandretur
noneoft hr
eevalues:TRUE,FALSE,or
Unknown.Waitami nute!Unknown?TRUEandFALSEar esel
f-
expl
anatory,butwhati
sUnknown?
Tounder st
andhow y oucouldgetanUnknown,y ouneedtoknow al i
tt
leabouttheconceptof
NULL.IndatabasetermsNULLi stheabsenceofdatainafi
eld.I
tdoesnotmeanacol umnhasa
Okor
onkwoM.
CCOS421Not
eBPage29of29
zeroorabl ankinit.Azer oorabl anki savalue.NULLmeansnot hingisinthatfi
eld.Ifyoumakea
compar i
sonl i
keFi el
d=9andt heonl yvaluef orFi eldisNULL,t hecompar i
sonwi llcomeback
Unknown.BecauseUnknowni sanuncomf ortabl
econdi ti
on, mostflav
orsofSQLchangeUnknown
toFALSEandpr ovideaspeci aloperator,I
SNULL, t
ot estforaNULLcondi ti
on.
Here'sanexampl eofNULL: Supposeanent ryint hePRI CEt abl
edoesnotcont ainav aluefor
WHOLESALE.Ther esult
sofaquer ymi ghtlookliket his:
SQL>SELECT*FROM PRI CE;
I
TEM WHOLESALE
-
---
--
--
--
--
-----
--
--
--
-
TOMATOES .34
APPLES .
23
ORANGES
Noticethatnothingisprintedoutint heWHOLESALEf iel
dposi t
ionfororanges.Thev aluefort
he
fi
eldWHOLESALEf ororangesi sNULL.TheNULLi snot i
ceableinthiscasebecausei tisina
numer i
ccolumn.Howev er,iftheNULLappear edi ntheI TEM column, i
twouldbei mpossi bl
etotel
l
thediff
erencebet weenNULLandabl ank.
TrytofindtheNULL:
SELECT*
2FROM PRI CE
3WHEREWHOLESALEI SNULL;

ITEM WHOLESALE
ORANGES
Asy oucanseebyt heout put,ORANGESist heonl yit
em whosev alueforWHOLESALEi sNULLor
doesnotcont ai
nav alue.Whatifyouusetheequal sign(=)instead?
SELECT*
FROM PRI CE
WHEREWHOLESALE=NULL;
nor owsselect ed
Youdi dn'
tfindanythingbecauset hecompar i
sonWHOLESALE=NULLr etur
nedaFALSE- -t
he
resultwasunknown.I twouldbemor eappropr i
atetouseanI SNULLi nsteadof=,changingthe
WHEREst atementtoWHEREWHOLESALEI SNULL.I nthi
scasey ouwoul dgetal
ltherowswher e
aNULLexi sted.
Thisexampl ealsoill
ust r
atesboththeuseoft hemostcommoncompar isonoper
ator,theequal
sign(=),andt hepl
ay groundofallcompari
sonoper at
ors,theWHEREcl ause.Youalreadyknow
aboutt heWHEREcl ause,sohere'sabri
eflookatt heequal sign.

Equal(=)
Earl
i
ery ousawhowsomeimplementati
onsofSQLusetheequal
signintheSELECTcl
auset
o
assi
gnanal i
as.I
ntheWHEREclause,t
heequalsi
gni
sthemostcommonl yusedcompari
son
operat
or.Usedal
one,t
heequalsi
gnisaveryconv
eni
entwayofselect
ingoneval
ueoutofmany
.
Trythi
s:
SQL>SELECT*FROM FRI ENDS;

LASTNAME FI
RSTNAME AREACODEPHONE ST ZI
P
BUNDY AL 100 555-
1111I
L 22333
MEZA AL 200 555-
2222UK
MERRI
CK BUD 300 555-
6666CO 80212
MAST JD 381 555-
6767LA 23456
BULHER FERRI
S 345 555-
3223I
L 23332
Let
'sf
indJD'
srow.(
Onashor
tli
stt
hist
askappear
str
ivi
al,
buty
oumayhav
emor
efr
iendst
hanwe
Okor
onkwoM.
CCOS421Not
eBPage30of30
do-
-ory
oumayhaveali
stwit
hthousandsofr
ecor
ds.
)
SELECT*
FROM FRI
ENDS
WHEREFIRSTNAME=' JD'
;
LASTNAME FI
RSTNAME AREACODEPHONE ST ZI
P
MAST JD 381 555-
6767LA 23456
Wegotther
esul
tthatweexpect
ed.
Tr
ythi
s:
SELECT*FROM FRIENDS
WHEREFI RSTNAME='AL'
;
LASTNAME FI
RSTNAME AREACODEPHONE ST ZI
P
BUNDY AL 100 555-
1111I
L 22333
MEZA AL 200 555-
2222UK

NOTE:Hereyouseethat=canpull
inmul t
ipl
erecords.Noti
cet hatZI
Pisbl
ankonthesecond
r
ecord.ZI
Pisacharact
erfi
eld,
andinthispart
icul
arrecordt
heNULLdemonst rat
esthataNULLi
n
acharact
erf
iel
disi
mpossibletodi
ffer
enti
atefrom ablankfi
eld.

Her
e'sanotherveryimportantl
essonconcer
ningcasesensi
ti
vi
ty:
SELECT*FROM FRI ENDS
WHEREFI RSTNAME=' BUD'
;
FIRSTNAME
BUD
Nowtrythi
s:
select*from fri
ends
wherefirst
name=' Bud'
;
nor
owssel ected.

EventhoughSQLsy nt
axisnotcasesensiti
ve,dat
ais.Mostcompaniesprefertostoredatain
uppercasetoprovi
dedataconsi
stency.Youshouldal
waysstor
edataeitherinalluppercaseori
n
al
llowercase.Mixi
ngcasecreat
esdiff
icul
ti
eswheny outr
ytoretr
iev
eaccur atedata.

Great
erThan(>)andGreat
erThanorEqualTo(
>=)
Thegreat
erthanoper
ator(
>)worksl
i
kethis:
SELECT*
FROM FRIENDS
WHEREAREACODE>300;
LASTNAME FI
RSTNAME AREACODEPHONE ST ZI
P
MAST JD 381 555-
6767LA 23456
BULHER FERRI
S 345 555-
3223I
L 23332
Thi
sexampleli
stal
lthear
eacodesgr
eat
ert
han(
butnoti
ncl
udi
ng)300.Toi
ncl
ude300,
typet
his:
SELECT* FROM FRIENDS
WHEREAREACODE>=300;
LASTNAME FI RSTNAME AREACODE PHONE ST ZIP
BUNDY AL 100 555-
1111IL 22333
MAST JD 381 555-
6767LA 23456
BULHER FERRIS 345 555-
3223IL 23332
Wit
hthischangeyougetar
eacodesst
art
ingat300andgoi
ngup.Youcoul
dachi
evet
hesame
r
esult
swiththest
atementAREACODE>299.

NOTE:Not
icet
hatnoquot
essur
round300i
nthi
sSQLst
atement
.Number
-def
inedf
iel
dsdonot
Okor
onkwoM.
CCOS421Not
eBPage31of31
r
equi
requot
es.

LessThan(<)andLessThanorEqualTo(
<=)
Thesecompari
sonoperat
orswor
kthesamewayas>and>=wor
k,onl
yinr
ever
se:
SELECT*
2FROM FRI ENDS
3WHERESTATE<' LA'
;
LASTNAME FI
RSTNAME AREACODEPHONE ST ZI
P
BUNDY AL 100 555-
1111 I
L 22333
MERRI
CK BUD 300 555-
6666CO 80212
BULHER FERRI
S 345 555-
3223I
L 23332

Waitaminute.Di
dyoujustuse<onachar act
erfi
eld?Ofcour
sey oudid.Youcanuseanyoft
hese
operat
orsonanydatatype.Theresul
tvar
iesbydataty
pe.Forexample,uselower
casei
nthe
fol
lowi
ngstatesear
ch:
SELECT*
2FROM FRI ENDS
3WHERESTATE<' l
a';

LASTNAME FI
RSTNAME AREACODEPHONE ST ZI
P
BUNDY AL 100 555-
1111 I
L 22333
MEZA AL 200 555-
2222UK
MERRI
CK BUD 300 555-
6666CO 80212
MAST JD 381 555-
6767LA 23456
BULHER FERRI
S 345 555-
3223I
L 23332
Noti
cethatUpper
caseisusual
l
ysortedbef
orel
ower
case;t
heref
ore,
theupper
casecodesr
etur
ned
ar
elessthan'l
a'
.Agai
n,tobesafe,
checkyouri
mpl
ementat
ion.

Toi
ncl
udet
hestateofLoui
sianai
ntheori
ginal
sear
ch,
type
SELECT*
2FROM FRIENDS
3WHERESTATE<=' LA'
;
LASTNAME FI
RSTNAME AREACODEPHONE ST ZI
P
BUNDY AL 100 555-
1111 I
L 22333
MERRI
CK BUD 300 555-
6666CO 80212
MAST JD 381 555-
6767LA 23456
BULHER FERRI
S 345 555-
3223 I
L 23332

Inequali
ti
es( <>or!=)
Wheny ouneedt of i
ndev eryt
hingexceptforcertai
ndata,usetheinequal
i
tysy
mbol,whi
chcanbe
eit
her<>or! =,dependingony ourSQLi mplement ati
on.Forexample,t
ofi
ndever
yonewhoisnot
AL,typethis:
SELECT*FROM FRI ENDS
WHEREFI RSTNAME<>' AL';
Tof i
ndev ery
onenotl i
vi
ngi nCalif
ornia,
typethis:
SELECT*FROM FRI ENDS
WHERESTATE! ='CA';
Youcanusebot hsymbol s,<>and! =,
canexpr ess"notequal
s."

Char
acterOper
ators
Youcanusecharact
eroper
ator
stomani
pul
atet
hewaychar
act
erst
ri
ngsar
erepr
esent
ed,
bot
hin
Okor
onkwoM.
CCOS421Not
eBPage32of32
theoutputofdataandintheprocessofplaci
ngcondi
ti
onsondatat
ober et
riev
ed.Thi
ssect
ion
descri
bestwocharacteroperat
ors:t
heLIKEoperat
orandthe|
|oper
ator
,whichconvey
sthe
conceptofcharact
erconcatenat
ion.

TheLIKE
Whatify
ouwantedtoselectpar
tsofadatabasethatfi
tapatternbutwer
en'tqui
teexactmatches?
Youcoul
dusetheequalsignandrunt
hroughallthepossi
blecases,butt
hatprocesswouldbe
bor
ingandti
me-consumi
ng.Inst
ead,y
oucoul duseLIKE.Considert
hefol
lowing:
SQL>SELECT*FROM PARTS;

NAME LOCATI
ON PARTNUMBER
APPENDI
X MI
D-STOMACH 1
ADAMSAPPLE THROAT 2
HEART CHEST 3
SPI
NE BACK 4
ANVI
L EAR 5
KI
DNEY MI
D-BACK 6
Howcanyouf
indal
lthepar
tsl
ocat
edi
ntheback?Tr
ythi
s:
SQL>SELECT*FROM PARTS
WHERELOCATIONLIKE'
%BACK%'
;

Youcanseet heuseoft hepercentsign( %)i


nt hestatementafterLI
KE.Whenusedi nsi
deaLIKE
expressi
on, %isawildcard.Whaty ouaskedf orwasanyoccur renceofBACKi nthecolumn
l
ocat i
on.Ifyouqueri
ed
SQL>SELECT*
FROM PARTS
WHERELOCATI ONLI KE'BACK%' ;
youwoul dgetanyoccur rencethatstart
edwi t
hBACK:
Ifyoutype
SQL>SELECT*
FROM PARTS
WHERENAMELI KE'A%';
youwoul dgetanynamet hatstart
swi thA.
IsLIKEcasesensiti
ve?
Theansweri syes.Referencest odataarealway scasesensit
ive.
Whati fyouwanttofinddat athatmat chesallbutonecharacterinacert
ainpatt
ern?Inthi
scase
youcoulduseadi ff
erentt ypeofwildcard:t
heunder score.

Under
score(_
)
Theunder
scorei
sthesi
ngl
e-char
act
erwil
dcar
d.Usi
ngamodi
fi
edversi
onoft
het
abl
eFRI
ENDS,
ty
pethi
s:
Tofi
ndallt
herecor
dswher
eSTATEst ar
tswit
hC,ty
pet
hefol
l
owing:
SQL>SELECT*
2FROM FRI
ENDS
3WHERESTATELI
KE'
C_'
;
LASTNAME FI
RSTNAME AREACODEPHONE ST ZI
P
MERRI
CK BUD 300 555-
6666CO 80212
PERKI
NS ALTON 911 555-
3116CA 95633
BOSS SI
R 204 555-
2345CT 95633
Youcanusesev
eral
under
scor
esi
nast
atement
:
Okor
onkwoM.
CCOS421Not
eBPage33of33
SQL>SELECT*
2FROM FRI
ENDS
3WHEREPHONELI
KE'
555-
6_6_
';
LASTNAME FI
RSTNAME AREACODEPHONE ST ZI
P
MERRI
CK BUD 300 555-
6666CO 80212
MAST JD 381 555-
6767LA 23456
Thepr
eviousst
atementcoul
dal
sobewri
tt
enasf
oll
ows:
SQL>SELECT*
2FROM FRIENDS
3WHEREPHONELI KE'
555-
6%'
;

Thet
wowi l
dcardscanbecombi
nedt
of i
ndal
lrecor
dswi
thLast
hesecondchar
act
er:
SQL>SELECT*
2FROM FRIENDS
3WHEREFI RSTNAMELIKE'
_L%'
;

LASTNAME FI
RSTNAME AREACODE PHONE ST ZIP
BUNDY AL 100 555-
1111 I
L 22333
MEZA AL 200 555-
2222 UK
PERKI
NS ALTON 911 555-
3116CA 95633

Concatenat
ion(
||
)
The||(
doublepi
pe)sy
mbol
concat
enat
est
wost
ri
ngs.
Tryt
his:
SQL>SELECTFI
RSTNAME|
|LASTNAMEENTI
RENAME
2FROM FRI
ENDS;
ENTI
RENAME
AL BUNDY
AL MEZA
BUD MERRI
CK
JD MAST
FERRI
S BULHER
ALTON PERKI
NS
SI
R BOSS
7rowssel ected.
Noti
cethat||isusedi nst
eadof+.I
fyouuse+t oconcatenatethest
ri
ngs,
theSQLinter
preterused
f
orthisexampl e(PersonalOr
acl
e7)ret
urnsthefol
lowingerror
:
SQL>SELECTFI RSTNAME+LASTNAMEENTI RENAME
FROM FRI ENDS;
ERROR:
ORA- 01722:invali
dnumber
I
tisl
ookingf ortwonumber stoaddandthrowstheerrorinv
ali
dnumberwhenitdoesn'
tfindany.

NOTE:Somei mpl
ementat
ionsofSQLuset heplussignt
oconcat
enat
est
ri
ngs.Checky
our
i
mplementat
ion.
Her
e'samorepracti
cal
exampleusingconcatenati
on:
SELECTLASTNAME|
|'
,'
||FI
RSTNAMENAME
FROM FRI
ENDS;
NAME
BUNDY ,
AL
MEZA ,
AL
Okor
onkwoM.
CCOS421Not
eBPage34of34
MERRI
CK ,
BUD
MAST ,
JD
BULHER ,
FERRI
S
PERKI
NS,
ALTON
BOSS ,
SIR
7r owsselect
ed.
Thi
sst
atementinsert
edacommabet
weent
hel
astnameandt
hef
ir
stname.

NOTE:Noticetheext
raspacesbet
weenthef i
rstnameandt helastnameintheseexamples.
Thesespacesareactual
l
ypartoft
hedata.Withcer t
aindat
atypes,spacesar
eright
-paddedt
o
val
ueslessthanthet
otall
engthal
l
ocat
edf oraf i
eld."

Sofaryouhaveper
for
medt hecomparisonsoneatati
me.Thatmethodisf
ineforsomeprobl
ems,
butwhatify
ouneedtofindal
lthepeopleatworkwi
thlastnamesst
art
ingwit
hPwhohav eless
thant
hreedaysofHol
idayti
me?

LogicalOperators
l
ogicaloperatorssepar
atetwoormorecondi
ti
onsintheWHEREclauseofanSQLst
atement
.
Holi
dayt i
mei salwaysahottopi
caroundt
heworkplace.Sayy
oudesi
gnedatabl
ebelowcal
l
ed
HOLIDAYf ortheaccounti
ngdepart
ment:
SQL>SELECT*FROM HOLI
DAY;
OUTPUT:
LASTNAME EMPLOYEENUM YEARSLEAVETAKEN
ABLE 101 2 4
BAKER 104 5 23
BLEDSOE 107 8 45
BOLI
VAR 233 4 80
BOLD 210 15 100
COSTALES 211 10 78
6rowsselected.
Supposeyourcompanygiveseachempl oyee12daysofl
eav
eeachyear
.Usi
ngwhatyouhav
e
l
earnedandalogicaloper
ator
,tofindal
ltheemploy
eeswhosenamesst
artwi
thBandwhohave
morethan50daysofl eav
ecomi ng.
SQL>SELECTLASTNAME,
2YEARS*12-LEAVETAKENREMAI
NING
3FROM HOLI
DAY
4WHERELASTNAMELI
KE'
B%'
5AND
6YEARS*12-LEAVETAKEN>50;
TheSELECTcl ause( li
nes1and2)usesar it
hmet icoperator
stodet er
minehowmanyday sofleave
eachempl oyeehasr emai ning.Thenormal precedencecomput esYEARS*12-LEAVETAKEN.( A
clearerapproachwoul dbet owr i
te(YEARS*12)-LEAVETAKEN. )
LIKEi susedi nl i
ne4wi t
ht hewi l
dcard%t ofindalltheBnames.Li ne6usest he>tofindal
l
occur r
encesgr eaterthan50.
Thenewel ementi sonl i
ne5.Youusedt hel ogicaloperat
orANDt oensurethatyoufoundrecords
thatmett hecr iteri
ainl i
nes4and6.
AND
ANDmeanst hatt heexpr essionsonbot hsidesmustbet ruetor eturnTRUE.Ifei
therexpr
essi
onis
false,ANDr etur nsFALSE.Forexampl e,t
of indoutwhi chempl oyeeshav ebeenwiththecompany
for5y earsorl essandhav etakenmor ethan20day sleave,
trythis:
SQL>SELECTLASTNAME
Okor
onkwoM.
CCOS421Not
eBPage35of35
2FROM HOLI
DAY
3WHEREYEARS<=5
4AND
5LEAVETAKEN>20;
I
fyouwanttoknowwhichemploy
eeshavebeenwi
tht
hecompanyf
or5y
ear
sormor
eandhav
e
t
akenl
essthan50per
centofthei
rleav
e,y
oucoul
dwri
te:
SQL>SELECTLASTNAMEWORKAHOLI
CS
2FROM HOLI
DAY
3WHEREYEARS>=5
4AND
5(
(YEARS*
12)
-LEAVETAKEN)
/(YEARS*12)<0.
50;
Checkthesepeopl
eforbur
nout
.Al
socheckouthowweusedt
heANDt
ocombi
net
heset
wo
condi
ti
ons.

OR
Youcanal
souseORtosum upaseriesofcondit
ions.Ifanyoft
hecompar
isonsi
str
ue,ORr
etur
ns
TRUE.Toi
l
lust
rat
ethedi
ff
erence,
condit
ionsrunthelastquerywi
thORi
nsteadofwi
thAND:
SQL>SELECTLASTNAMEWORKAHOLI
CS
2FROM HOLI
DAY
3WHEREYEARS>=5
4OR
5(
(YEARS*
12)
-LEAVETAKEN)
/(YEARS*12)>=0.
50;
Theori
ginalnamesar esti
lli
nthelist
,buty
ouhavethr
eenewentri
es(whowoul dprobabl
yresent
bei
ngcalledworkaholi
cs).Thesethreenewnamesmadetheli
stbecausetheysati
sfi
edoneoft he
condi
ti
ons.ORr equi
resthatonlyoneofthecondi
ti
onsbetr
ueinorderfordat
atober et
urned.

NOT
NOTmeansjustthati
fthecondit
ionitappli
estoeval
uat
estoTRUE,NOTmakeitFALSE.I
fthe
condi
ti
onaf
tert
heNOTi sFALSE,itbecomesTRUE.Forexampl
e,t
hefol
lowi
ngSELECTretur
nsthe
onl
ytwonamesnotbeginningwithBi nthetabl
e:
SQL>SELECT*
2FROM HOLI
DAY
3WHERELASTNAMENOTLI
KE'
B%'
;
NOTcanalsobeusedwit
htheoperat
orI
Swhenappl
iedtoNULL.Recal
lthePRI
CESt
abl
ewher
e
weputaNULLvaluei
ntheWHOLESALEcolumnopposi
tethei
tem ORANGES.
Tof
indthenon-
NULLit
ems,typet
his:
SQL>SELECT*
2FROM PRI
CE
3WHEREWHOLESALEI
SNOTNULL;

SetOperat
ors
OnDay1, "
Int
roduct
iontoSQL,
"youl
ear
nedt
hatSQLi
sbasedont
het
heor
yofset
s.Thef
oll
owi
ng
sect
ionsexaminesetoper
ator
s.

UNIONandUNI ONALL
UNIONreturnstheresul
tsoft
woquer
iesmi
nust
hedupl
i
cat
erows.Thef
oll
owi
ngt
wot
abl
es
repr
esenttherost
ersofteams:
SQL>SELECT*FROM FOOTBALL; SQL>SELECT*FROM SOFTBALL;
NAME NAME
ABLE ABLE
Okor
onkwoM.
CCOS421Not
eBPage36of36

BRAVO BAKER
CHARLI
E CHARLI
E
DECON DEAN
EXI
TOR EXI
TOR
FUBAR FALCONER
GOOBER GOOBER
7r
owssel
ect
ed.

Howmanydi
ff
erentpeopl
epl
ayononet
eam oranot
her
?
SQL>SELECTNAMEFROM SOFTBALL
2UNI
ON
3SELECTNAMEFROM FOOTBALL;
NAME
ABLE
BAKER
BRAVO
CHARLI
E
DEAN
DECON
EXI
TOR
FALCONER
FUBAR
GOOBER
10rowsselected.
UNIONr etur
ns10di sti
nctnamesf r
om thet
wolist
s.Howmanynamesar eonbothl
i
sts(
incl
udi
ng
dupli
cates)?
Thecombi nedl
ist-
-courtesyoft
heUNI ONALLstatement
--
has14names.UNIONALLworksj
ust
l
ikeUNI ONexceptitdoesnoteliminat
edupli
cat
es.Nowshowmeal istofpl
ayer
swhoar
eonbot h
teams.Youcan'tdot hatwithUNION--
youneedtolear
nINTERSECT.

I
NTERSECT
I
NTERSECTr etur
nsonlytherowsfoundbybothquer
ies.ThenextSELECTstat
ementshowsthe
l
i
stofplayerswhoplayonbot ht
eams:
SQL>SELECT*FROM FOOTBALL
2I NTERSECT
3SELECT*FROM SOFTBALL;
I
nthi
sexampl eINTERSECTfindstheshor
tli
stofpl
ayerswhoareonbot ht
eamsbycombiningt
he
r
esul
tsofthet woSELECTstatements.

MINUS( Dif
ference)
Minusretur
nst herowsfr
om thefi
rstquerythatwerenotpresenti
nthesecond.Forexample:
SQL>SELECT*FROM FOOTBALL
2MI NUS
3SELECT*FROM SOFTBALL;
Theprecedingqueryshowsthethreefootball
play
erswhoar enotonthesoft
ballt
eam.Ifyou
rev
ersetheor der
,yougett
hethreesoftball
player
swhoar en'
tonthefoot
ballt
eam:
SQL>SELECT*FROM SOFTBALL
2MI
NUS
3SELECT*FROM FOOTBALL;
NAME
BAKER
Okor
onkwoM.
CCOS421Not
eBPage37of37
DEAN
FALCONER

Miscel
laneousOperat
ors:INandBETWEEN
Thetwooper at
orsI
NandBETWEENpr ovi
deashor t
handforfuncti
onsyoualreadyknowhowt odo.
I
fyouwant edtofi
ndfri
endsinCol orado,Cali
for
nia,
andLouisi
ana, y
oucouldtypethefol
l
owing:
SQL>SELECT*
2FROM FRI ENDS
3WHERESTATEI N('
CA',
'CO','
LA')
;
Thesecondexampleisshorterandmor ereadabl
ethanthefi
rst.Youneverknowwheny oumight
havetogobackandwor konsomet hingyouwr ot
emonthsago.I Nalsoworkswi t
hnumbers.

I
fyouneededarangeoft
hingsfr
om t
hePRI
CEt
abl
e,y
oucoul
dwr
it
ethef
oll
owi
ng:
SQL>SELECT*
2FROM PRICE
3WHEREWHOLESALE>0. 25
4AND
5WHOLESALE<0. 75;

Usi
ngBETWEEN, youwoul
dwr
it
ethi
s:
SQL>SELECT*
2FROM PRICE
3WHEREWHOLESALEBETWEEN0.
25AND0.
75;
togett
hesameresult
I
TEM WHOLESALE
TOMATOES .
34
POTATOES .
51
BANANAS .
67
TURNI
PS .
45
Agai
n,t
hesecondexampl
eisacl
eaner
,mor
ereadabl
esol
uti
ont
hant
hef
ir
st.

NOTE:IfaWHOLESALEval
ueof0.25exist
edi
nthePRICEtabl
e,t
hatrecor
dwouldhavebeen
r
etr
iev
edalso.Par
amet
ersusedi
nt heBETWEENoperat
orarei
nclusi
veparamet
ers.

SQLEXI STS
TheEXI STScondit
ionisconsidered"t
obemet "i
fthesubquer
yr etur
nsatleastonerow.EXI
STS
operatorsi
mplytestswhethertheinnerquer
yret
urnsanyrow.Ifitdoes,t
hentheouterquer
y
proceeds.I
fnot,t
heout erquerydoesnotexecut
e,andtheenti
reSQLst atementret
urnsnot
hing.

Sy
ntax:
Sel
ectcol
umnsf
rom t
abl
eswher
eexi
sts(
subquer
y);

Ret
ri
evet
heent
ir
eempl
oyeeNamesandEmpnoi
nal
lthedepar
tment
s.

SQL>SELECTempno, eNameFROM Empe


WHEREEXI STS(SELECT1
FROM deptWHEREe. deptno=dept.
dept
no);
Foreachrowf r
om theEMPt able,t
hecondi
ti
onischeckedwhet
hert
her
eexi
stsar
owi
nEMPt
abl
e
thathastheemployees.

•Li
stal
ltheemploy
eesdet
ail
whodonotmanageany
one
SQL>SELECTENAME,
JOBFROM EMPE
Okor
onkwoM.
CCOS421Not
eBPage38of38
WHERENOTEXISTS(SELECT*FROM EMPWHEREE.MGR=E.
EMPNO)
;
Out
putwi
l
lbethedet
ail
ofal
ltheempl
oyeessuchast
hei
rnameandj
ob.

Exer
cises
UsetheFRIENDSt abletoanswerthef oll
owingquestions.
1.Writ
eaquer ythatret
urnsevery
onei nt hedatabasewhoselastnamebegi
nswithM.
2.Writ
eaquer ythatret
urnsevery
onewhol i
vesinIl
li
noiswit
hafir
stnameofAL.
3.Gi
ventwot ables(PART1andPART2)cont ai
ningcolumnsnamedPARTNO, howwoul
dyouf
ind
outwhichpartnumber sareinbot
ht ables?Wr i
tethequery.
4.Whatshorthandcouldy ouuseinsteadofWHEREa>=10ANDa<=30?
5.Whatwillt
hisqueryreturn?
SELECTFI
RSTNAME
FROM FRI
ENDS
WHEREFI
RSTNAME='
AL'
ANDLASTNAME='
BULHER'
;
1.Usi
ngtheFRIENDStable,wri
teaquer ythatr
etur
nst
hef
oll
owi
ng:
NAME ST
AL FROM I
L
2.Usi
ngtheFRIENDStable,wri
teaquer ythatr
etur
nst
hef
oll
owi
ng:
NAME PHONE
MERRICK,BUD 300-
555-6666
MAST,JD 381-555-6767
BULHER,FERRI
S 345-555-3223
Okor
onkwoM.
CCOS421Not
eBPage39of39

TRANSACTI
ON,
CONCURRENCYa
ndRECOVERYMa
nag
eme
nt
Tr
ansactionManagement
o At ransaction i
sacol l
ecti
onofoper at
ionst hatper formsasi ngl
el ogi
calf uncti
oni na
databaseappl i
cati
on
o Tr ansact i
on-managementcomponentensur esthatt hedatabaseremainsi naconsi stent
(correct)stat
edespit
esy st
em fai
lures(e.g.,powerf ail
uresandoperati
ngsy stem crashes)
andt ransacti
onfai
lur
es.
o Concur rency-
contr
olmanagercont r
ol st
hei nter
actionamongt heconcurrenttransactions,
toensur etheconsist
encyofthedatabase.
o Sy stem recover
y-istheprocessofr est
oringadat abaset othecorr
ectstateintheev entof
afailure.

Tr
ans
act
ion
At r
ansact i
oni sapar tofprogr am execut
ionthataccessesandupdat esv ar
iousdataitems.
At ransacti
oncanbedef i
nedasagr oupoft asksi nwhi chasi nglet askist heminimum
processinguni tofwor k,whichcannotbedi videdf urther.
At r
ansact i
oni sal ogicalunitofwor kthatcontainsoneormor eSQLst atements.
At r
ansact i
oni sanat omicuni t(t
ransacti
oneithercompl ete0%or100%) .
Adat abaset ransact ionmustbeat omic,meani ngt hatitmustbeei therenti
rel
ycompl etedor
aborted.
Atransact i
oni sanexecut ionofauserpr ogr
am,andi sseenbyt heDBMSasaser iesorli
stof
act
ions.Theact ionst hatcanbeexecut edbyat ransact ionincluder
eadsandwr i
tesofdatabase
obj
ects,wher easact ionsi nanor di
naryprogram coul dinvolveuseri nput,accesst onetwork
devi
ces, userinterfacedr awing, et
c.

Definiti
onofsomet ransact ionConcept s&Ter minologi es
(a)At omi citymeansat r
ansact i
onexecut eswhenal lact ionsoft het ransact ionarecompl eted
full
y ,ornonear e.Thi smeanst herear enopar ti
alt ransact ions( suchaswhenhal ft heact i
ons
compl eteandt heot herhal fdonot ).
(b)Consi st encyi nv ol vesbegi nningat ransact ionwi tha’ consi stent’ dat abase, andf i
nishingwi tha
’consi st ent’dat abase.Forexampl e,i nabankdat abase,moneyshoul dnev erbe“ created”or
“deleted”wi thoutan appr opriate deposi torwi thdr awal .Ev er yt ransact ion should see a
consi stentdat abase.
(c)I solation ensur est hatat r
ansact i
oncanr uni ndependent ly,wi thoutconsi deri
nganysi de
effectst hatot herconcur r
ent l
yr unni ngt ransact i
onsmi ghthav e.
1.Whenadat abasei nterleav est ransact ionact ionsf orper f
or mancer easons,thedat abase
prot ectseacht ransact ionf rom t heef f
ectsofot hert r ansact ions.
(d)Dur abilitydef inest heper sistenceofcommi tteddat a:onceat ransact ioncommi t
s,thedat a
shoul dper sisti nt hedat abaseev eni ft hesy stem cr ashesbef or et hedat ai swr i
ttentonon-
volatilest orage.
(e)Aschedul ei saser iesof( possi blyov erlapping)t r
ansact ions.
(f)Abl indwr iteiswhenat ransact ionwr itest oanobj ectwi thoutev erreadi ngt heobject .
(g)A di r
tyr eadoccur swhenat ransact ionr eadsadat abaseobj ectt hathasbeenmodi f
iedby
anot hernot -yet-commi t
tedt ransact ion.
(h)Anunr epeat abler eadoccur swhenat ransact i
oni sunabl etor eadt hesameobj ectv aluemor e
thanonce,ev ent hought het ransact ionhasnotmodi fiedt hev alue.Supposeat ransactionT2
changest hev al ueofanobj ectAt hathasbeenr eadbyat r
ansact ionT1whi leT1i sst i
l
lin
progr ess.I fT1t riest oreadt hev al
ueofAagai n,i
twi l
lgetadi ff erentr esult
,event houghi thas
notmodi fiedA.
()A ser
i ializableschedul e ov erasetS oft ransact i
onsi saschedul ewhoseef fectonany
consi stentdat abasei nstancei si dent icalt ot hatofsomecompl eteser i
alschedul eov erthe
setofcommi ttedt ransact ionsi nS.
Okor
onkwoM.
CCOS421Not
eBPage40of40
(
j)A recover
able scheduleis one i n which a t
ransaction can commi tonl yafteral
lother
tr
ansacti
onswhosechangesi thasr eadhavecommi t
ted.
(
k)Aschedulethatavoids-
cascading-abortsisoneinwhicht ransact
ionsonlyreadthechangesof
commi t
tedtransact
ions.Suchaschedul eisnotonl yrecov er
able,abor
ti
ngat ransact
ioncan
beaccomplishedwithoutcascadingt heabortt
oot hertransacti
ons.

3.St
ri
ct2PList
hemostwi delyusedlocki
ngpr ot
ocolwher
e
1)Atr
ansact
ionrequestsashared/excl
usivel
ockontheobjectbef
orei
treads/modi
fi
est
he
obj
ect
.
2)Al
ll
ocksheldbyat r
ansacti
onarer el
easedwhenthetr
ansacti
oniscompleted.

4.Thephant om pr oblem i sasit


uat i
onwhereat ransact
ionretri
evesacol l
ectionofobjectstwi ce
butseesdi ff
erentr esults,eventhoughitdoesnotmodi fyanyoft heseobj ectsit
sel
fandf ol
lows
thest ri
ct2PLpr otocol .Thisproblem usual
lyarisesindy namicdat abaseswher eat ransaction
cannotassumei thasl ockedallobjectsofagiventype(suchasal lsailor
swi thrank1;newsai lors
ofr ank1canbeaddedbyasecondt r
ansact
ionaf t
eronetransacti
onhasl ockedalloftheor i
ginal
ones) .
Ifthesetofdat abaseobj ect
sisfixedandonlythev al
uesofobjectscanbechanged, t
hephant om
problem cannotoccursi nceonecannotinser
tnewobj ectsintothedat abase.

ACI
Dpr
ope
rti
esofTr
ans
act
ion

Atomicity
 Ei theral loperationsoft hetransact i
onar epr oper l
yr efl
ectedinthedat abaseornonear e.
 Meansei theralltheoper ati
onsofat ransact ionar eexecut edornotasi ngleoperat
ionis
execut ed.
 Forexampl econsi derbelowt ransactiont ot ransferN50f rom accountAt oaccountB:
1.r ead(A)
2.A: =A–50
3.wr it
e( A)
4.r ead(B)
5.B: =B+50
6.wr it
e( B)
I
nabov et ransact i
onifN50i sdeduct edfrom accountAt henitmustbeaddedt oaccountB.
Consi
st ency
 Execut ionofat ransacti
oni nisolati
onpr eser vestheconsi stencyoft hedatabase.
 Meansourdat abasemustr emai ninconsi stentstat eaft
erexecut i
onofanyt r
ansacti
on.
 I nabov eexampl etotalofAandBmustr emai nsamebef oreandaf tertheexecuti
onof
transact i
on.
I
solat
ion
 Al thoughmul t
ipletransactionsmayexecut econcur rentl
y,eacht r
ansact i
onmustbe
unawar eofot herconcur rentlyexecutingt ransact i
ons.
 I ntermedi atetransact i
onr esultsmustbehi ddenf rom otherconcur r
ent l
yexecuted
transact i
ons.
 I nabov eexampl eoncey ourtransacti
onst artf r
om st eponei tsr
esultshouldnotbeaccess
byanyot hertransactionunt i
llaststep( step6)i scompl eted.

Dur
abi
l
ity
 Afteratransacti
oncompletessuccessful
l
y,t
hechangesi
thasmadetothedatabase
persist
,evenifther
earesystem f
ail
ures.
 Oncey ourtransact
ioncomplet
edupt ostep6it
sresul
tmustbest
oredpermanentl
y.I
t
Okor
onkwoM.
CCOS421Not
eBPage41of41
shoul
dnotber
emov
edi
fsy
stem f
ail
s.

Stat
eTr ansiti
onDiagram (
orTransact
ionSt at
eDiagram).
Becausef ail
ureoftr
ansact
ionmayoccur, t
ransact
ionisbrokenupi
ntost
atest
ohandl
evar
ious
sit
uat i
ons.
Thefollowingarethedif
fer
entstat
esintransacti
onprocessingi
ndat
abase
Active
Parti
alcommi t
ted
Fail
ed
Aborted
Commi t
ted

Active
Thi sist heinitial state.Thet ransactionst aysinthisstatewhi l
eitisexecut i
ng.
Par t
iall
yCommi tted
Thi sist hest at eaf t
ert hefinalstatementoft hetransacti
oni sexecut ed.
Att hi
spoi ntf ailurei ssti
llpossiblesi ncechangesmayhav ebeenonl ydonei nmai nmemor y,a
hardwar ef ailurecoul dsti
lloccur .
TheDBMSneedst owr i
teoutenoughi nfor
mat i
ont odisksot hat, i
ncaseofaf ail
ure,t
hesy stem
couldr e-
cr eat et heupdat esper formedbyt hetransacti
ononcet hesy stem isbroughtbackup.
Af terithaswr ittenoutal lt
henecessar yinf
ormation,iti
scommi tted.
Failed
Af terthedi scov eryt hatnormal execut ioncannol ongerproceed.
Onceat ransact ioncannotbecompl eted,anychangest hatitmademustbeundoner ol
l
ingi t
back.
Abor ted
Thest ateaf tert het r
ansactionhasbeenr olledbackandt hedat abasehasbeenr est
oredt oits
statepr i
ort ot hest artofthet ransaction.
Commi tted
Thet r
ansact i
onent ersinthisstateaf tersuccessf ul
compl eti
onoft hetransact
ion.
Wecannotabor torr oll
backacommi t
tedt r
ansaction.

S
che
dul
e
Ascheduleisthechronologi
cal(sequenti
al)or
derinwhi
chinstr
uctionsareexecutedinasy st
em.
Ascheduleforasetoft ransacti
onmustconsi stofal
ltheinst
ructionofthosetransacti
onsand
mustpreservetheorderinwhichtheinstr
ucti
onsappeari
neachi ndivi
dualtr
ansaction.
Exampleofschedule(Schedule1)
T1 T2
read(
A)
A:=A-50
writ
e(A)
Okor
onkwoM.
CCOS421Not
eBPage42of42
read(
B)
B:=B+50
writ
e(B)

read(
A)
temp:A*0.1
A:=A-temp
writ
e(A)
read(
B)
B:=B+temp
writ
e(B)

Seri
alschedul
e
ThisisaSchedulethatdoesnoti nter
leavetheacti
onsofdif
ferenttr
ansacti
ons.
Inschedule1,all
theinstr
uct i
onsofT1ar egroupedandruntogether.Thenall
theinst
ruct
ionsof
T2ar egroupedandrunt ogether.
Meansschedul e2willnotstartunti
lallt
heinstr
ucti
onsofschedule1ar ecomplet
e.Thist
y peof
schedulesiscal
ledseri
al schedul
e.

I
nterl
eavedschedule
Schedulethatint
erl
eavetheact i
onsofdif
ferenttr
ansacti
ons.
Meansschedul e2canst artbefor
ealli
nstr
uctionsofschedul
e1ar
ecompl
eted.Thi
sty
peof
schedulesiscal
ledint
erleavedschedul
e.

T1 T2
read(
A)
A:=A-50
writ
e(A)

read(
A)
temp:A*0.
1
A:=A-t
emp
writ
e(A)
read(
B)
B:=B+50
writ
e(B)
read(
B)
B:=B+temp
writ
e(B)

Equival
entsc
hedul es
Twoschedul esar eequival
entscheduleiftheeffectofexecut
ingthefi
rstschedul
eisi
dent
ical
(same)totheef fectofexecuti
ngthesecondschedul e.
Wecanal sosayt hatt
woschedul eareequi v
alentschedulei
ftheoutputofexecut
ingt
hefi
rst
schedulei
si dentical
(same)totheout putofexecutingthesecondschedule.

Ser
ial
izablesc
hedul e
Aschedul ethatisequival
ent(
init
sout
come)t
oaser
ial
schedul
ehast
heser
ial
i
zabi
l
itypr
oper
ty.
Exampl eofserial
izabl
eschedule
Okor
onkwoM.
CCOS421Not
eBPage43of43

I
nabov eexampl
ether
earetwoschedul
esasschedul
e1andschedule2.
I
nschedule1andschedul
e2theorderi
nwhichthei
nstr
ucti
onsoftr
ansact
ionareexecut
edi
s
notthesamebutwhatev
ert
heresul
twegetissame.Sothi
sisknownasserial
i
zabil
it
yof
tr
ansacti
on.

Twopha s
ec ommi tpr otocolandwor kingoft wopha sec ommi tpr ot ocol.
Twophas ec ommi tpr otocol
o •Thet wophasecommi tprot ocol prov i
desanaut omat icr ecov erymechani sm incasea
o sy stem ormedi af ai
lureoccur sdur ingexecut i
onoft het r
ansact i
on.
o •Thet wophasecommi tprot ocol ensur est hatallparticipant sper formt hesameact i
on
o ( ei
thert ocommi tort orollbackat ransact i
on) .
o •Thet wophasecommi tstrategyi sdesi gnedt oensur ethatei theral lt
hedat abasesar e
o updat edornoneoft hem, sot hatt hedat abasesr emai nsy nchr oni zed.
o •I ntwophasecommi tprot ocol t
her ei sonenodewhi chi sactasacoor di
nat orandall
o ot herpar ticipat i
ngnodear eknownascohor tsorpar ti
cipant .
o •Coor dinat or–t hecomponentt hatcoor dinateswi thal lthepar ticipants.
o •Cohor ts( Par t
icipants)–eachi ndiv i
dual nodeexceptcoor dinatorar epar ti
cipant.
o •Ast henamesuggest s,t
het wophasecommi tprotocol inv ol v
est wophases.
1.Thef ir
stphasei sCommi tRequestphaseORphase1
2.Thesecondphasei sCommi tphaseORphase2
Commi tReques tPhas e( Obtai
ningDec isi
on)
Tocommi tt het r ansaction,thecoor dinatorsendsar equestaski ngf or“ r
eadyf orcommi t
”to
eachcohor t.
Thecoor di nat orwai tsunt ili
thasr ecei vedar eplyf rom allcohor tst o“v ote”ont her equest
.
Eachpar ticipantv otesbysendi ngamessagebackt ot
hecoor dinat orasf ol
lows:
ItvotesYESi fiti spr eparedt ocommi t
Itmayv oteNOf oranyr easoni fitcannotpr eparet hetransact ionduet oal ocal f
ailur
e.
Itmaydel ayi nv ot ingbecausecohor twasbusywi t
hot herwor k.
Commi tPhas e( Per formi ngDec i
sion)
Ifthecoor di natorr eceivesYESr esponsef rom al lcohor t
s,itdeci dest ocommi t.Thet r
ansacti
on
isnowof ficiallycommi t
ted.Ot herwise, iteitherr eceiv
esaNOr esponseorgi vesupwai ti
ngfor
somecohor t,soi tdecidest oabor t.
Thecoor di nat orsendsi tsdecisiont oal l parti
cipant s(i
.e.COMMI TorABORT) .
Par t
icipant sacknowl edger eceiptofcommi toraboutbyr epl yingDONE.

S
yst
emr
ecove
ry
Databaser ecover
yisthepr
ocessofrest
ori
ngadatabasetothecorr
ectstat
eint
heeventofa
f
ailure.
Databaser ecover
yisaservi
cethati
sprovi
dedbyt
heDBMSt oensurethatt
hedat
abaseis
r
eliableandr emai
ninconsi
stentst
atei
ncaseofafail
ure.
Okor
onkwoM.
CCOS421Not
eBPage44of44
Rest oringaphy sical backupmeansr econst r
uct i
ngitandmaki ngi tavail
abl etot hedat abase
ser ver.
Tor ecov erarestor edbackup, dataisupdat edusi ngr edocommandaf t
ert hebackupwast aken.
Dat abaseser versuchasSQLser verorORACLEser verperformscashr ecov eryandi nstance
recov eryaut omat i
callyafteraninstancef ailure.
I
ncaseofmedi af ail
ure,adat abaseadmi nistrator(DBA)musti nit
iatear ecov eryoper ati
on.
Recov eri
ngabackupi nvol
v estwodi stinctoper ati
ons: rol
li
ngthebackupf orwar dt oamor e
recentt i
mebyappl yingredodat aandr oll
ingbackal lchangesmadei nuncommi tt
ed
transact i
onst otheiror i
ginalstate.
I
ngener al,r
ecov eryr efer
st othev ari
ousoper ationsinvolvedinr estori
ng, r
ol l
ingf orwardand
rolli
ngbackabackup.
Backupandr ecov er yrefer
st ot hevariousst rategiesandoper ationsinv olvedi npr otect
ingthe
dat abaseagai nstdat alossandr econst r
uctingt hedat abase.

Logba s edr ecove ryme thod.


Logbas edr ecover y
Themostwi delyusedst ructuref orr ecor dingdatabasemodi ficationi st helog.
Thel ogi sasequenceofl ogr ecor ds, recor dingalltheupdat eact ivi
tiesi nthedat abase.
Inshor tTr ansact i
onl ogi saj ournal orsimpl yadat af i
l
e,whi chcont ainshi storyofallt
ransact
ion
per formedandmai ntainedonst ablest orage.
Sincet hel ogcont ainsacompl eter ecor dofal ldatabaseact ivity,thev olumeofdat astor
edinthe
logmaybecomeunr easonabl elar ge.
Forl ogr ecor dst obeusef ulforrecov eryf r
om sy stem anddi skf ail
ures, thelogmustr esi
deon
stabl est orage.
Logcont ains
1.St artoft ransact ion
2.Tr ansact ion- i
d
3.Recor d-id
4.Ty peofoper ati
on( i
nser t
, updat e,del et
e)
5.Ol dv alue, newv alue
6.Endoft ransact iont hati scommi ttedorabor ted.
Allsuchf ilesar emai nt ainedbyDBMSi tself.Normal lythesear esequent ialfi
les.
Recov eryhast wof act or sRol lback( Undo)andRol lforward( Redo) .
Whent ransact ionTi star ts,itregist ersitselfbywr itnga<Ti
i st art>logr ecor d
Bef oreTi execut eswr ite(X) ,al ogr ecor d<Ti ,X,V1, V2>i swr it
ten, wher eV1i sthev al
ueofX
bef or ethewr i
te, andV2i sthev aluet obewr i
tt
ent oX.
Logr ecor dnot est hatTi hasper formedawr i
teondat ait
em Xj
Xj hadv alueV1bef or et hewr ite,andwi llhav evalueV2af terthewr ite.
WhenTi fi
nishesi tlastst atement ,thel ogr ecord<Ti commi t>i swr itten.
Twoappr oachesar eusedi nlogbasedr ecov ery
1.Def erreddat abasemodi fi
cation
2.I mmedi at edat abasemodi fi
cat i
on

Logbas
edRec
over
yTec
hni
ques
Onceaf ai
lureoccurs, DBMSr etri
evesthedatabaseusingtheback-
upofdatabaseand
tr
ansacti
onl og.Variouslogbasedr ecoverytechni
quesusedbyDBMSar easperbel
ow:
1.DeferredDat abaseModi fi
cati
on
2.Immedi at
eDat abaseModi f
icat
ion
Bothofthetechniquesuset r
ansactionlogs.Thesetechni
quesareexpl
ainedinf
oll
owingsub-
sect
ions.

De
fer
redDa
taba
seModi
fi
cat
ionl
ogba
sedr
ecove
ryme
thod.
Okor
onkwoM.
CCOS421Not
eBPage45of45
Concept
Updat es(changes)tot hedatabasear edef err
ed(orpostponed)until
thet r
ansact i
oncommits.
Duringt heexecut
ionoft ransact i
on, updatesarerecordedonlyinthetransacti
onl ogandin
buffers.Aft
erthet r
ansact i
oncommi ts,theseupdatesarerecordedinthedat abase.
Whenf ailur
eoccurs
Ift
ransact i
onhasnotcommi tt
ed, theni thasnotaffectedthedatabase.Andso, noneedtodo
anyundoi ngoper at
ions.Justr estartthet r
ansacti
on.
Ift
ransact i
onhascommi tt
ed,then, sti
ll,
itmaynothav emodi fi
edthedat abase.Andso,redothe
updat esofthetransaction.

Transact
ionLog
I
nt histechnique,tr
ansact
ionlogisusedinfoll
owingway s:
TransactionTst art
sbywr i
ti
ng<Tst art
>tothelog.
Anyupdat eisrecor
dedas<T, X,V>,whereVindicatesnewvaluefordatait
em X.Here,noneed
topreser veoldvalueoft
hechangeddat ait
em.Al so,Visnotwri
ttentotheXindatabase,buti
t
isdeferred.
TransactionTcommi tsbywrit
ing<Tcommi t>tothelog.Oncethi
si senter
edi
nl og,
actual
updatesar erecordedtothedatabase.
I
fat ransactionTabor t
s,t
hetransacti
onlogrecordisignor
ed,andnoanyupdat esarerecor
ded
tothedat abase.

Example
Considerthefol
l
owingtwot r
ansact
ions,
T0andT1giveni
nfi
gur
e,whereT0execut
esbef
oreT1.
Alsoconsidert
hatini
ti
alv
aluesforA,BandCare500,
600and700respect
ivel
y.

Thefoll
owingfi
gur
eshowst
het
ransact
ionl
ogf
orabov
etwot
ransact
ionsatt
hreedi
ff
erent
i
nstancesofti
me.

I
ffai
l
ureoccursincaseof
1.NoanyREDOact ionsar
erequi
red.
2.AsTransact
ionT0hasalr
eadycommi t
ted,
itmustberedone.
3.AsTransact
ionsT0andT1havealr
eadycommitt
ed,theymustber
edone.

Syst
emr e c
ove ryprocedurewi t
hChe ckpointrecordconcept.
Problemswi thDeferred&I mmedi ateUpdat es
Sear chingt heentir
el ogistime-consumi ng.
Iti
spossi bletoredot ransacti
onst hathav ealr
eadybeenst oredthei
rupdatestot
hedatabase.
Checkpoi nt
Apoi ntofsy nchronizati
onbetweendat abaseandt ransact
ionlogfil
e.
Speci fi
est hatanyoper ationsexecutedbef orethi
spoi ntar
edonecor rect
lyandst
oredsafel
y.
Okor
onkwoM.
CCOS421Not
eBPage46of46
Atthi
spoi nt,allt
hebuf f
ersar ef orce-f
ullywrit
tentot hesecondar ystorage.
Checkpoi ntsar escheduledatpr edetermi nedti
mei ntervals
Usedt olimi t-
1.Thesizeoft r
ansact ionlogf i
le
2.Amountofsear ching,and
3.Subsequentpr ocessi ngt hatisrequiredtocarryoutont het ransactionlogfil
e.
Whenf ailureoc curs
Fi
ndoutt henear estcheckpoi nt.
I
ftransact ionhasal r
eadycommi tt
edbef orethischeckpoi nt
,ignor eit
.
I
ftransact ionisactiv
eatt hi
spoi ntoraf terthi
spoi ntandhascommi tt
edbef or efail
ure,r
edothat
t
ransact ion.
I
ftransact ionisactiv
eatt hi
spoi ntoraf terthi
spoi ntandhasnotcommi tted, undothat
t
ransact i
on.
Exampl e
Considert het r
ansactionsgi veni nfoll
owi ngfi
gure.Her e,Tcindicat escheckpoi nt,whileTf
i
ndicatesf ai l
uretime.
Here,atfai l
uret i
me-
1.Ignoret het ransacti
onT1asi thasal r
eadybeencommi tt
edbef orecheckpoi nt.
2.Redot ransact ionT2andT3ast heyareact i
veat/af t
ercheckpoi nt,buthav ecommi ttedbefor
e
fail
ure.
3.Undot r
ansact i
onT4asi tisact i
v eaft
ercheckpoi ntandhasnotcommi t
ted.

Conc
urr
enc
ycont
rol
?WhyConc
urr
enc
ycont
rol
isne
ede
d?
Concur
rencyc ont
rol
Thetechniqueisusedtoprot
ectdatawhenmul ti
pleuser
sar
eaccessi
ng(
usi
ng)samedat
a
concur
rentl
y(atsametime)i
scal
ledconcur
rencycont
rol.

Concurrenc
ycontr
olneeded
Iftr
ansacti
onsareexecutedseri
all
y,i.
e.,sequenti
all
ywi t
hnoov erl
apinti
me,notransact
ion
concurr
encyexist
s.However,i
fconcur
renttransact
ionswithint
erl
eav
ingoper
ati
onsar
eallowedin
anuncont r
oll
edmanner,someunexpected,undesirabl
er esul
tmayoccur.Herear
esomet ypi
cal
examples:

1.Thelostupdat
epr oblem:Thi
sproblem i
ndicat
esthati
ftwot r
ansacti
onsT1andT2bot hread
thesamedataandupdat eitt
heneff
ectoffi
rstupdat
ewill
beov er
wri
ttenbythesecondupdate.
2.Thedir
tyreadproblem:Thedir
tyreadar
iseswhenonet r
ansact
ionupdatessomeitem andthen
Okor
onkwoM.
CCOS421Not
eBPage47of47
fai
lsduet osomer eason.Thi supdat edi tem isr etr
ievedbyanot hertr
ansactionbef oreitis
changedbackt otheor i
ginalvalue.
3.Thei ncorrectretri
ev alproblem:Thei nconsistentretri
evalpr obl
em ar i
seswhenonet r
ansact
ion
retr
ievesdatat ousei nsomeoper at
ionButbef oreitcanuset hisdataanothert r
ansactionupdate
thatdat aandcommi ts.Thr ought hischangewi l
lbehi ddenf r
om f ir
sttr
ansact i
onandi twil
l
continuet ousepr ev i
ousr etri
ev eddata.Thi sprobl em isalsoknownasi nconsistentanaly
sis
problem.
Mosthi gh-performancet ransact i
onalsystemsneedt or unt r
ansact i
onsconcur r
entlytomeet
thei
rper formancer equirement s.Thus,wi thoutconcur rencycont r
olsuchsy st
emscannei t
her
providecorrectresultsnormai ntainthei
rdatabasesconsi stent.

De fi
neloc k, l
ockingandl oc
kba se
dpr otocol
.
Loc k
Al ockisav ari
ableassociatedwithdat aitem tocontrolconcur
rentaccesstothatdatai
tem.
Lockr equest sar emadet oconcur r
ency -
cont r
olmanager .
Transact ioncanpr oceedonl yaft
errequesti sgranted.
Loc king
Onemaj orproblem indatabasesisconcur r
ency.
Concur rencypr oblemsar i
sewhenmul tipl
euser strytoupdat eorinsertdataint
oadat abase
table att he same t ime.Such concur r
entupdat es can cause datat o become corr
uptor
i
nconsi st ent.
Lockingi sastrategythatisusedt opreventsuchconcur r
entupdatestodata.
Loc kbas edpr otocol
Al ockisamechani sm tocontrolconcurrentaccesst oadataitem

Dataitemscanbel ockedint womodes:


1.Excl usive(X)mode.Dat aitem canbebot hreadaswel laswr i
tten.X-l
ockisr equestedusi ng
lock-Xinstr
uct i
on.
2.Shar ed( S)mode.Dat aitem canonl yber ead.S-
lockisrequestedusinglock-Si nstr
uction.
Lockr equestsar emadet oconcur rency-cont r
olmanager .
Transact i
oncanpr oceedonl yaf terrequesti sgranted.
Lock-compat ibil
i
tymat r
ix
S X
S TRUE FALSE
X FALSE FALSE
At ransactionmaybegr antedal ockonani t
em iftherequestedlocki scompat i
blewi t
hl ocks
alr
eadyhel dont hei tem byot hert ransactions
Anynumberoft ransactionscanhol dshar edlocksonani tem,buti fanytransact i
onhol dsan
exclusiveont hei t
em noot hert ransact i
onmayhol danyl ockonthei tem.
Ifalockcannotbegr anted,t her equest i
ngt r
ansacti
onismadet owai tti
llal
lincompat ibl
el ocks
heldbyot hertransact i
onshav ebeenr eleased.Thel ocki
st hengranted.
Okor
onkwoM.
CCOS421Not
eBPage48of48

Wri
te(
A)
Unl
ock(A)
Thi
slockingprotocol di
vi
destransactionexecut ionphaseintothr
eepar t
s.
1.Int hefir
stpart,whentransactionst art
sex ecuti
ng,t
ransacti
onseeksgr antf
orlocksit
needsasi texecutes.
2.Secondpar tiswherethetransact i
onacqui resalll
ocksandnoot herlockisrequi
red.
Transacti
onkeepsexecut ingi tsoperati
on.
3.Assoonast hetransact
ionreleasesi tsfi
rstlock,t
hethir
dphasest art
s.Inthi
sphasea
t
ransacti
oncannotdemandf oranyl ockbutonl yrel
easestheacquiredlocks.

Met
hodst
ocont
rolc
onc
urr
enc
y
Met
hodst
ocont
rolc
onc
urr
enc
y(Mec
hani
sms
)
Opt imist ic-Delayt hechecki
ngofwhet herat r
ansact
ionmeetst hei solati
onandotheri nt
egrit
y
rules( e.g.,ser
ial
izabil
i
tyandrecov er
abili
ty)unti
lit
send,wit
houtbl ockinganyofits(read,wri
te)
oper ationsandt henabortat r
ansact i
ont opreventt
hev i
olat
ion,ift hedesir
edrulesar etobe
violateduponi t
scommi t.Anabor tedt r
ansacti
onisimmedi atelyr estar
tedandr e-execut
ed,
whi ch i ncursan obv iousoverhead.I fnott oo manyt r
ansactionsar eabort
ed,t hen being
opt i
mi sticisusuallyagoodstrategy.

Pessimisti
c-Blockanoperati
onofatransact
ion,
ifitmaycausev i
olat
ionoftherul
es,unt
ilt
he
possibi
li
tyofvi
olat
iondi
sappears.Bl
ocki
ngoperationsi
st y
pical
l
yinvolv
edwi t
hperfor
mance
reducti
on.
Semi -
opti
misti
c-Blockoperat
ionsinsomesituat
ions,i
ftheymaycausev iol
ati
onofsomer ul
es,
Okor
onkwoM.
CCOS421Not
eBPage49of49
anddonotbl
ockinot
hersi
tuat
ionswhi
l
edel
ayi
ngr
uleschecki
ng(
ifneeded)t
otr
ansact
ion'
s
end,
asdonewit
hopti
misti
c.

Met
hodst
ocont
rolc
onc
urr
enc
y(Met
hods
)
Locking( Two-phasel ocking-2PL)-Cont r
oll
ingaccesst odat abylocksassi gnedt othedat
a.
Accessofat ransacti
ont oadat ai t
em (dat
abaseobject )lockedbyanot hertr
ansact i
onmaybe
blocked( dependingonl ocktypeandaccessoper ati
ont ype)unt i
ll
ockr elease.
Serial
izati
ongr aphchecki ng(alsocal l
edSerial
izabi
li
tyorConf li
ctorPr ecedencegr aph
checking)-Checki ngforcy cl
esi ntheschedule'sgr
aphandbr eaki
ngt hem byabor t
s
Timest ampor dering(TO)-Assi gningtimestampst otransact i
ons,andcont roll
i
ngorchecking
accesst odatabyt imest ampor der.
Commi tmentor deri
ng( Commi tor deri
ngorCO)-Cont r ol
li
ngorchecki ngtransactions'
chronologicalorderofcommi teventstobecompat i
blewi ththeirrespectiv
epr ecedenceor
der
.

Thr
eepr
obl
emsduet
oconc
urr
enc
yandHowt
hepr
obl
emsc
anbea
voi
ded.
Thr
eepr
obl
emsduet
oconc
urr
enc
y
1.Thelostupdatepr
obl
em: Thi
sproblem i
ndicat
ethatift
wotransact
ionsT1andT2bothr eadt
he
samedat aandupdat
eitthenef f
ectoffi
rstupdat
ewillbeover
writ
tenbythesecondupdate.
Howt oavoid:I
nexamplebelow, atr
ansacti
onT2mustnotupdat ethedatai
tem (
X)unti
lthe
tr
ansacti
onT1cancommi tdatait
em (X).

2.Thedir
tyreadproblem: Thedir
tyreadari
seswhenonetr
ansacti
onupdatesomeitem andt
hen
fai
lsduetosomer eason.Thisupdatedit
em isr
etr
iev
edbyanothert
ransact
ionbef
orei
tis
changedbacktotheor i
ginalv
alue.

Howt oavoi
d:I
naboveexampl
eatransact
ionT1mustnotr
eadt
hedat
ait
em (
X)unt
ilt
he
t
ransact
ionT2cancommitdat
ait
em (X).

3.Thei ncor
rectr
etri
evalpr
oblem:Theinconsi
stentret
ri
evalpr obl
em ari
seswhenonet r
ansact
ion
retr
ievesdatatouseinsomeoper at
ionbutbef
oreitcanuset hisdataanothertr
ansacti
onupdates
thatdat aandcommi ts.Throughthischangewi l
lbehi ddenf r
om fi
rsttransact
ionandi twil
l
continuetousepr evi
ousretri
eveddata.Thisproblem isal soknownasi nconsi
stentanaly
sis
Okor
onkwoM.
CCOS421Not
eBPage50of50
pr
obl
em.

Dat
abaseAdmi
nist
rat
or
Coordinatesallt
heacti
vi
ti
esofthedatabasesyst
em;thedat
abaseadmi
nist
rat
orhasagood
understandingoftheent
erpr
ise’
sinf
ormati
onresour
cesandneeds.

DBA-i sDatabaseAdminist
rat
or.
DatabaseAdmini
str
atorisapersoni
ntheor
gani
zat
ionwhocont
rol
sthedesi
gnandt
heuseof
database.

Functi
onsorResponsi
bil
it
iesofDBAa reasunde r
:
SchemaDefi
nit
ion
DBAdef i
nesthelogi
calschemaoft hedat abase.
Aschemar eferstot
heov eral
ll
ogicalstr
uctureoft hedat
abase.
Accordi
ngtot hi
sschema, dat
abasewi l
lbedesi gnedtostor
erequi
reddat
aforanor
gani
zat
ion.

St
orageSt ruc t
ur eandAc ces sMethodDef initi
on
DBAdeci deshowt hedat ai stober epr esentedint hedat abase.
Basedont his, st oragest ructur
eoft hedat abaseandaccessmet hodsofdatai
sdefined.
Defi
ningSec ur ityandI nt egr it
yCons tr
ai nts
DBAdeci desv arioussecur it
yandi ntegr i
tyconstraints.
DDLpr ovidesf aci l
iti
est ospeci f
yingsuchconst r
aints.
Granti
ngofAut hor i
zationf orDat aAc ces s
TheDBAdet er mi neswhi chuserneedsaccesst owhi chpar tofthedatabase.
Accor dingt ot hi s,varioust ypesofaut horizat
ions(per missions)aregrant
edtodiff
erentuser
s.
Thisi srequiredt opr eventunaut horizedaccessofadat abase.
Li
aisonwi t
hUs er s
DBAi sresponsi bletopr ov i
denecessar ydat atouser .
Usershoul dbeabl etowr i
tetheext ernal schema, usingDDL.
Assi
stingAppl ic ationPr ogr ammer s
DBApr ovidesassi stancet oappli
cat ionpr ogrammer st odev el
opapplicat
ionprogr
ams.
MonitoringPer f
or manc e
TheDBAmoni t orsper f
or manceoft hesy stem.
Okor
onkwoM.
CCOS421Not
eBPage51of51
TheDBAensur esthatbett
erperfor
manceismaint
ainedbymakingchangei
nphysicalorl
ogi
cal
schemai frequired.
BackupandRec over y
Databaseshoul dnotbelostordamaged.
ThetaskofDBAi stobackingupt hedat
abaseonsomest oragedevi
cessuchasDVD,CDor
MagneticTapeorr emoteserver
s.
Incaseoff ail
ures,suchasfloodorvir
usat
tack,
Databasei
srecover
edfr
om t
hisbackup.

Di
ff
ere
nti
atet
heDAa
ndDBA.

You might also like