You are on page 1of 18

Uni

ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

CHAPTER1 mor
edi
ff
icul
t.
 Lackofsecur
it
yandl
i
mit
eddat
ashar
ing
Int he past ,f i
l
e sy stems are used by a managerofany smal l
organizationt otr acknecessar ydata.Tr adit
ional
ly,fi
l
esy stemsar e Dat ashar ingandsecur i
tyar ecl oselyrelat
ed.Dat ashar i
ngamong
composedofacol l
ectionoff i
l
ef ol
dersthatar eproperl
yt agged,kept sev eralsepar ateduser smayi nvit
eal otofsecur it
yri
sks.Thereare
i
naf i
l
ingcabi net,andor gani
zedaccordingt othei
rlogi
cal r
elati
onships. al
t ernat i
vesf orf i
lesecur i
tysuchasusi ngspr eadsheets.Butthen,
Asanor ganizati
onexpandsanddat aneedsbecomel arger
,thef il
e user soff il
esy st
emsdon’ tuset hem thatof t
en,thus,resul
ti
ngtothe
system wasconv ertedf r
om manualt oacomput eri
zedone.Fr om this, dissol uti
onofuserl evelaccess.
data pr ocessing ( DP) speci ali
sts emer ged to creat e necessary  Ext ensivePr ogrammi ng
comput erf i
lest r
uct ures,writ
esof t
waret hatmanaget hedat awi t
hin Changi nganexi stingf il
est ruct ureinaf il
esy stem envir
onmentis
diffi
cul tsinceitrequirestheDPspeci ali
stto:
thosest ructures,anddesi gnt heappli
cat i
onpr ogramst hatpr oduce
r eadt herecordf rom theor iginalfi
le,
report
sbasedont hef i
ledata.
transf
orm the ori
ginaldat
ato conf
orm t
othe new st
ruct
ure’
s
Asmal l
fil
esyst
em ev ol
vedasthenumberoffil
esincr
eased.Asshown, st
oragerequi
rements,
eachfil
ei nt
hesy stem useditsownapplicat
ionprogramst ostor
e, 
wr
it
ethet
ransf
ormeddat
aint
othenewf
il
est
ruct
ure,
and
ret
ri
eve,andmodifydata.Al
so,eachfi
lewasownedbyt heindi
vi
dualor
depar
tmentthatcommi ssi
oneditscr
eati
on. repeatthesecond,t
hir
d,andf
our
thst
epsf
oreachr
ecor
dint
he
or
igi
nalfi
le.

Becauseoft
hesepr
obl
ems,usi
ngt
hedat
abasesy
stem becamev
ery
desi
rabl
e.

Databasesy stem isat ermref


erri
ngtoanor gani
zati
onofcomponents
thatdefi
neandr egulatethecoll
ecti
on,st
orage,management,anduse
ofdatawi thinadat abaseenvir
onment.Itisacomput er
izedsyst
em
whose ov eral
lpur pose ist o maint
aininformat
ion and make t
hat
i
nformationav ai
lableondemand.

The f ive maj or par ts of a dat abase sy stem f rom a gener al


managementpoi ntofv iewar e: har dwar e,sof twar e,peopl e, procedur es,
anddat a.
Har dwar ei dent if i
es al lt he sy stem’ s phy sicaldev i
ces.The mai n
har dwar ecomponentofadat abasesy stem i sthecomput erandal l
otherper i
pher alst hatcont r
ol comput eri nputandout put .
Sof twarer eferst ot hecol lectionofpr ogramsusedbyt hecomput ers
withi nthedat abase.Ther ear et hr eet ypesofsof twar eneededf orthe
dat abasesy stem t of ull
yf unct ionandt hesear eoper at i
ngsy stems
sof tware,DBMS sof twar e,and appl ication pr ograms and ut il
ity
sof tware.Oper at i
ng sy st
ems sof twar e manages al lt he har dwar e
component sandmakesal ltheot hersof twar er unont hecomput er.
Ex ampl esoft hissof twar ear eMi crosof tWi ndows,Li nux,MacOS,
UNI X,andMVS.DBMS sof twar emanagest hedat abasewi thint he
Computerizedf i
lesystemshav ebeenagr eati
mprovementoverthe
dat abasesy st em.Someexampl esar et heMS SQLSer v er,Or acle,
manualsy stem.Itser vedausef ulpurposeindat
amanagementf or
My SQL,and I BM’ s DB2.Last ly,appl icat i
on pr ograms and ut i
l
iti
es
overt
wodecadesi nthecomput erera.
sof twarear eusedt oaccessandmani pul atedat ai nt heDBMS.I tis
Fil
esystemsbecameobsol eteduet oprobl
emsandl i
mit
ati
onsthat
alsousedt omanaget hecomput erenv ironmentwher et hedat aaccess
comewit hit.Iti
snecessarytobei nformedaboutt
heseshort
comings andmani pulationt akepl ace.Appl i
cat i
onpr ogr amsar emost lyusedt o
fori
twil
llety ouunderstandt
hedev elopmentofmoder
ndatabases. accessdat afrom wi t
hint hedat abaseandt hen, uset hatdat at oai din
thedeci si
onmaki ngpr ocesst hroughgener atingr epor ts,tabul ati
ons,
andot heri nfor mat ion.Ont heot herhand,ut i
li
ti
esar esof twar et ools
 Lengt hydev el
opmenttime usedi nhel pingmanaget hecomput ercomponent soft hedat abase
I
nf i
lesystems, eventhesimplestdata-retr
ievaltaskrequi
resext
ensi
ve syst em.
programmi ng.Witholderfi
lesystems,pr ogrammer sneededtospeci
fy Thet erm“ peopl e”r eferst oal ltheuser soft hedat abasesy st em.The
whatmustbedoneandhowi twillbedone. fi
v et ypesofdat abasesy stem user sbasedonpr imar yj obf unct ions
 Di ff
icul
tyofgetti
ngquickanswer s are:t hesy stemsadmi nistratorswhoover seet hegener aloper at i
onsof
Generati
ngadhocr eport
sisi mpossi blewi t
hf il
esy st
emssinceit
the dat abase sy stem;t he dat abase admi nistr
ators( DBAs) who
requi
resext ensiv
epr ogramming.I tcanev entakeweeksormont hs
managet heuseandpr operf unct i
onal ityoft hedat abasesy st em;t he
beforeDPspeci ali
ststoproducereports.
dat
abase

desi
gnerordatabasear
chi
tect
swhodesi
gnthedatabasestr
ucture;
Complexsyst
em admini
str
ati
on
thesyst
emsanalyst
sandpr
ogrammer
swhodesi
gnandimplementthe
Sinceadhocqueri
esareimpossibl
etomake,f i
l
er eport
ingprogr
ams
appli
cati
onpr
ograms–t hr
oughwhichaccessandmani
pul
ationofthe
madebyDPspeci al
i
ststendtocreateprogr
amsf oreachreport
ing
database’
si he end user
s done;and t s who use t
he appli
cat
ion
need.Asthenumberoffil
esexpand,syst
em administ
rati
onbecomes
Page1of1
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

programsf ort
hedailyoperationsoftheorgani
zati
on. form ofr
ules;
forexample:
Procedures arethe rul
es t hatgov ernthe desi
gn and use oft he Ast udent’
sGeneralWeight
edAv
erage(
GWA)mustbef
rom 1.
00t
o
databasesy st
em.Procedur esenforcestandar
dsonhowt hebusiness 5.00
willbeconductedwi t
hcust omer sandwi t
hintheorgani
zati
onaswel l
andar eusedt oensurethatt hemoni t
ori
ngandauditofbot hthedata Onecl assmusthav e40st udentsonly.
3.Beginwi ththehierar
chicaldatabasemodeldescr i
bedinSl i
de13.
thatenterthedatabaseandt heinformati
onproducedbyt hatdatais
Expl
aintheslide’
scontentusingtheinfor
mat ionbelow.
organized. Thehierarchi
caldatabasemodelwasdev elopedi nthe1960’s.Itwas
usedtomanagel ar
geamount sofdat af orcompl exmanuf act
uri
ng
Themet adatapr ovidesadescr i
pti
onofthedat achar act eri
sticsand proj
ects,andhasabasi clogi
calstruct
ureofanupsi de-
downt r
ee.
thesetofr el
ati
onshi psthatli
nkt hedataf
oundwi t
hint hedat abase.It 4.Sti
l
lont hesamesl i
de,explai
nthediagram pr esentedther
e.
provi
desinformationt hatcomplementsandexpandst hev alueanduse
ofthedata.Inot herwor ds,i
tpresentsamorecompl etedepi cti
onof Thest r
uctur
eofahi er
archi
caldat abasehasonl yonepar entbutcan
the datai nt he dat abase. For example,the met adat a st or
es havesev er
alchildr
en:eachpar entcanhav emanychi l
dren,buteach
i
nformati
onaboutt hedat aelementandt hetypeofv aluest oredon chi
ldhasonl yoneparentasshowni nthediagram ontheslide.
thatel
ement . Inotherwords,thismodeldepi ctsasetofone- t
o-manyr elat
ionshi
ps
Simplysaid,adat abasei sacol l
ecti
onofself
-descr
ibingdat a,si mi
lar bet
weenapar entandit
schil
drensegment s.
toawell-
organizedel ectr
onicfil
i
ngcabinet
. Asdepictedinthediagram,‘
FinalAssembl y’ortherootsegmenti sthe
par
entoft heLev el1segment s,which,inturn,arethepar entsofthe
Adat abasemodel defi
nest hel ogical desi gnofdat at hatcanbest ored, Level2segment sandsoon.
organized,andmani pulatedinadat abasesy stem.I ttherebydef i
nes
theinfrast r
uctureoffer
edbyapar ticul ardat abasesy stem. The net wor k model was cr eated t o r epresent compl ex dat a
Databasemodel saregr oupedi nt
ot wocat egor ies.Thef ir
stonei sthe rel
ationshi ps,impr ov edat abaseper formance,andi mposeadat abase
concept ualmodelwhi chf ocusesont hel ogicalnat ureoft hedat a standar d.Itisv erysi milart ot hehi erarchi calmodelsucht hatitalso
represent ati
on.I tis concer ned wi th whati sr epresented int he facil
i
tatesa1: *r elati
onshi ps.Howev er
,t henet workdat abaseal lows
database.Thesecondonei st hei mpl ement ationmodelwhi chplaces thechildt ohav esev eralpar ent s.
emphasi sonhowt hedat aarer epresent edi nt hedat abaseorhowt he The l ack of dat abase st andar ds made dat abase desi gns and
datastr ucturesareimpl ement edt or epr esentwhati smodel ed. appli
cat ionsl esspor tablef orpr ogr ammer s.Sot oest abli
shdat abase
Anexampl eofaconcept ualmodeli st heent ityrelati
onshipmodel standar ds,t he Conf er enceonDat aSyst emsLanguage( CODASYL)
while exampl es ofan i mplement at i
on modelar et he hier
archical establi
sheddat abasest andar dsbycr eatingt heDat abaseTaskGr oup
databasemodel ,networ kdatabasemodel ,relationaldatabasemodel , (DBTG)i nt hel ate1960st o def inest andar d speci fi
cati
onsf oran
andobj ect -
orient
eddat abasemodel . envir
onment t hat woul d f aci l
it
at e dat abase cr eati
on and dat a
mani pulation.
Thefol
lowingarethebasicbui
ldingblocksofadat abasemodel: The f i
nalDBTG r epor tcont ained speci fications f ort hree crucial
Enti
tyisanyt
hing(aperson,apl ace,
at hi
ng,oranev ent
)aboutwhich database component s such as t he net wor k schema,net work
dat
aar etobecol l
ect
edandst ored.Itr
epresentsapar ti
cul
arkindof subschema, anddat amani pul at i
onl anguage.
obj
ectinther ealworl
dt hatmayei t
herbeaphy sicalorconceptual The net workschema i st he concept ualor ganization oft he entir
e
obj
ect. database as v iewed by t he dat abase admi nistr
ator,t he networ k
subschemadef i
nest hepor tionoft hedat abase‘ seen’ bytheprograms
At t
ri
buteisthecharact
eri
sti
cofanentity
.Inotherwords,i
tdescri
bes thatpr oducet hedesi redi nfor mat ionf rom t hedat acont ainedwi thi
n
anent i
ty.Forexample,aSTUDENTent i
tymayhav eatt
ribut
essuchas thedat abase,andt heDMLdef i
nest heenv ir
onmenti nwhi chdatacan
studentnumber ,st
udentname,studentaddress,andstudentcont
act bemanaged.
number .
In1970,EdgarFrankCoddofI BM introducedt herelat
ional
model inhis
Relat
ionshipdescribest heassoci
ati
onamongent it
ies.Forexample, l
andmar kpaperent it
led‘ARel at
ionalModelofDat aforLargeShared
ast udent-teacherrelat
ionshipmaybedescr i
bedas:ast udentmay Databases’
.Ther el
ationalmodel producedan“ automatict
ransmissi
on”
attendclassesconduct edbysev er
alteachers,andeacht eachermay database.Itisa col l
ecti
on ofr elationsort wo-di
mensionaltabl
es
teach sev eralstudentsi n one cl
ass.Ther e aret hree types of havingdist
inctnames.I twasconsi der edi ngeniousbuti mpracti
cal
relat
ionshipsusedbydat abasemodelsandt heseare: becauseitr
equiredahi ghercomput erpower .
Thet abl
eint hesl i
der epresent
sar elati
onaldat abase.It
sr owsar e
One-t
o-manyrel
ati
onshipwhi chislabeledas1:*maybei ll
ust r
atedby cal
ledrecordswhi l
eitscolumnsar ecal edf
l ields.
thi
sexample:ast udentattendsdiffer
entclasses.Thest udentmay
att
endmanydi f
fer
entclassesbutst i
ll
,i
tisthesame‘ one’
st udentthat
Theent i
tyrel
at ionshipmodelwasi ntroducedbyPet erCheni n1976.It
att
endseachofthose‘many ’cl
asses.
yieldsagr aphi calrepresentati
onofent it
iesandt heirrelati
onshi psin
dat abasest r
uct ure.Itisusuallyr epresent edbyanent i
tyr elati
onship
Many-t
o-manyrel
ationshi
pwhi
chisl
abel
edas*:*maybedescr
ibed
diagram (whichwi ll
bedi scussedf urtheronsucceedi ngt opics).
byt
his:astudentmayl ear
nmanysubj
ect
s,andeachsubj
ectmaybe
The ent i
ty r elati
onship model i ntroduced t he t hree t ypes of
l
ear
nedbymanyst udents.
relati
onships:t heone- to-many( 1:*)r el
ationship,many -t
o-many( *:*
)
relati
onship,andone- t
o-one( 1:1)r el
at i
onshi p(whichwasdi scussed
One- t
o-onerel
ati
onshi
pwhi chislabeledas1:1maybedescr i
bedby prev i
ously)
.
thi
s:astudentmayonl ybeassignedwi thoneuniquestudentnumber. I
tal soisbasedont hef oll
owingcomponent s:theentit
y ,
at t
ributes,and
Inturn,auniquestudentnumbermayonl ybeownedbyaspeci fi
c
relati
onship(asdef i
nedear li
er).
student
.
Constr
aintisar estri
cti
on placed on the dat
a and isimportant
becausetheyhelpensuredataintegri
ty.Theyareusual
l
ywr it
teni
nt he

Page2of2
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

Theobj ect-
ori
entedmodelst oresbot hdat aandtheirrelati
onshipsina datacanbev iewed,updat ed,anddel et edbydi fferentuserscannow
singlestruct
ureknownasanobj ect.Itisbasedont hecomponent s beimpl ement ed.
suchas:obj ectwhi chisanabst r
actionofar eal
-worl
dent it
y,attr
ibute  Mul ti
useraccesscont rol
whi chdescri
best hepropertiesofanobj ect,cl
asswhichi sacol l
ection Userscannowshar ewi thdat acont ainedwi thinthedat abasewi t
hout
compr omi sing dat ai nt egrit
yand dat a consi stencybecauseoft he
ofsi mi
larobject
swi t
hshar edat t
ributesandmet hods,classhierarchy
sophisticat edal gor i
thm usedbyt heDBMS.
whi chreferstot hear rangementofcl asses,andi nherit
ancewhi ch  Backupandr ecov erymanagement
referstotheabil
ityofanobj ectwithintheclasshierarchytoinheritthe DBMSpr ov idesbackupanddat ar ecov erypr ocedur estoensur edata
attri
butesandmet hodsofthecl assesabov ei t
. safetyandi nt egr i
ty.
 Dat aint egr i
tymanagement
Basi
cDat
aModel
i
ngConcept
s DBMS el imi nat es dat a int egri
t y pr ogr ams and mi nimizes dat a
redundancybypr omot i
ngandenf orcingi nt
egr i
tyrules,andusi ngthe
Adat amodeli sther elati
velysimpler epresentati
onofamor ecompl ex datarelat i
onshi psst or edi nt hedat adi ctionary.
real-
worldobject.Themodel ’
smai nf unctionist ohelpusunder stand  Dat abaseaccessl anguagesandappl i
cationprogr ammi ng
thecompl exreal-
wor ldenv i
ronment .Also, i
trepresentsdatastructur es int erfaces
andt heircharacteristi
cs,relati
ons,const r
aints,andt ransf
ormat ions DBMS pr ov i
des dat a access v ia quer yl anguage whi ch i s a
withi
nt hedatabaseenv i
ronment.Wi thoutanappr opriatedatamodel , nonprocedur allanguageoronet hatletst heuserspeci f
ywhatmustbe
youwi l
lnotbeabl etocr eateagooddat abase. donewi t houthav i
ngt ospeci fyhowi tist obedone.I tsqueryl anguage
The Amer ican Nat i
onalSt andardI nstit
ute/Standards Planning and hastwocomponent s:t hedat adef i
niti
onl anguage( DDL)whi chdef i
nes
RequirementsCommi ttee( ANSI/SPARC)def inedt hr
eedi ff
erentdat a thestruct uresi nwhi cht hedat aar ehoused, andt hedat amani pul at
ion
l
anguage( DML)whi chal l
owsenduser st oext ractt hedataf r om the
model sbasedont heirdegreeofabst raction.Thesear etheconcept ual
database.DBMS al so pr ov i
des dat a access t o pr ogr
ammer sv i
a
model ,t
heinternalmodel ,andt heex t
ernal model . procedur al (3GL)l anguages.
 Dat abasecommuni cationint erfaces
Theext ernalmodeli stheend- user ’svi
ewoft hedat aenv ironment .By Data communi cat i
ons capabi li
ties ar e an essent ialfeature oft he

end- user ,wer efertot hosepeopl ewhouseappl i
cat i
onpr ogramst o DBMS.Cur rent-gener ation DBMS pr ov i
de speci alcommuni cat
ion
mani pulat edat aandgener atei nformat i
on.Theconcept ualmodeli s routi
nesdesi gnedt oal low t hedat abaset oacceptenduserr equests
usedt oi ntegrateal lexter
nalv iewsi nt
oasi ngl
ev i
ew.I trepresent sa withi
nacomput ernet wor kenv ir
onment .
globalv iewoft heent i
redatabaseandi sgraphical
lyr epresent edbyan
ERD.I tint egratestheent it
ies,relationshi
ps, constr
aints,andpr ocesses SinceaDBMSi shighl ydependentoni tsdat adi ct
ionary,l
etusdi scuss
i
nt oasi ngl eglobalv i
ewoft heent i
redataint heenter pr
ise.Last l
y ,the alitt
ledeeperaboutadat adict i
onar y
.
i
nt ernalmodelr epresentsthedat abaseas‘ seen’byt heDBMS.I not her Asdef i
nedi ntheI BM Di ctionar yofComput i
ng,adat adi ct
ionar yor
wor ds,i tr equi res the designert o mat ch the concept ualmodel ’
s met adatar eposit
or yi sacent r
alizedr eposi t
oryofi nformat i
onabout
datasuchasmeani ng,r elationshi pstoot herdat a,ori
gin,usage,and
char acteristi
csandconst r
ainttot hoseoft heselectedi mpl ement ation
format .
model . Thet wodat adictionar yty pesar ethei ntegr ateddat adicti
onar ywhi ch
i
si ncludedi ntheDBMS,andt hest andal onedat adicti
onarywhi chi sa
A dat
abasemanagementsystem i
sacol l
ect
ion ofpr
ogr
amsthat thir
d-par t
ydat adictionar yandi sasepar at esy stem fr
om theDBMS.
managesthedatabasest
ruct
ureand cont
rol
saccesstothedata Also,dat adicti
onar iescanbecl assif
iedasact i
veorpassi ve.Anact ive
st
oredint
hedat
abase. data di cti
onaryi s aut omat ically updat ed by t he DBMS by ev ery
databaseaccess,t hus,keepi ngi tsaccessi nformationupdat ed.Whi l
e
apassi v edat adi ctionar yi snotaut omat icall
yupdat edandusual l
y
 Dat adi cti
onar ymanagement requiresbat chprocessi ngt or un.
Allpr ogr amst hataccessdat aint hedat abasewor kthrought heDBMS
becauseofi tsdat adi cti
onarywher ethedef initi
onofdat ael ements CHAPTER2
andt hei rrelat i
onshi psar estored.TheDBMSusest hedat adi cti
onary
tol ookupt her equireddat acomponentst ruct uresandr elationshi
ps,
Ahi er
ar chicalstr
ucturei sanupsi de-down“ tr
ee”t hatrepr
esentsthe
theref orepr ev entingt oomuchcodi ngf orsuchcompl exr elat i
onships
basiclogi calst
ructureofahi erarchy .Itiscomposedofasegment ,a
i
n each pr ogr am.DBMS pr ovides dat a abst racti
on,and r emov es
parent
, andchi l
dren.
struct uralanddat adependencyf rom thesy stem.
Asegmenti stheequi valentofaf ilesy stem’sr ecordtype.Segments
 Dat ast oragemanagement
DBMS cr eat es t he compl ex structures requi red fordat a st or
age, canbeapar entorachi ld.Thepar enti sther ootsegment .I
tisthetop
theref oreel imi nat i
ngt heneedt odef i
neandpr ogram thephy sicaldata l
ayeroft hesegment .Thechi ldrenar et hesegment sbel ow ot
her
char act eri
stics. segment s.Eachpar entcanhav emanychi ldrenwhi leeachchil
dhas
 Dat at ransformat i
onandpr esentation onlyonepar ent
.
DBMSpr ov i
desappl icati
onpr ogramswi thsof twar eindependenceand
dataabst ract i
on.I ttransformst heent ereddat at oconf ormt ot hedata
struct urest hatar er equiredtost orethedat a.Thi sel
imi natest heneed
tomakeadi stincti
onbet weent hedat alogi calf or
matandt hedat a
phy sical format .
 Secur i
tymanagement
DBMShasasecur i
tysy stem thatenf orcessecur i
tyanddat apr i
vacy
withint hedat abase.Thi sisimpor tantforadat abasesy stem accessed
bysev eraluser sofdi ff
erentuseraccessl ev elsincecont rolofhow

Page3of3
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

XMLwascr eatedt ostructure,st or


e,andt r
anspor tinformationbutit
doesnotdoany thing.
XML was not desi gned f or dat abase appl i
cati
ons but si nce i
t
representsdat a,itisusefulasadat aformatwhenanappl i
cati
onmust
communi catewi thanot herappl icati
on,orintegrateinformat i
onf r
om
several ot
herappl icat
ions.
To br eaki tdown,pi ecebypi ece,mar kup referst o anything i
na
documentt hatisnoti ntendedt obepar tofthepr i
ntedout put.Markup
l
anguage, i
nel ectroni
cdat apr ocessing,i
saf ormaldescr ipti
onofwhat
partoft hedocumenti scont ent,whatpartismar kup, andwhatmar kup
means.

<Football
Team>
<TeamName>Azkal s</ TeamName>
Hierarchychartsar
ecr eatedbythepr ogrammert ohel pdocumenta <TeamMember >NeilEtheri
dge</
TeamMember >
program.Theyconv eyt hebigpictureoft hemodul es( orfuncti
ons) <TeamMember >RobGi er</
TeamMember >
usedi napr ogr
am.Itisar epr
esentati
onoft heinf
ormationcontained <TeamMember >Antondel Rosar
io</
TeamMember >
i
nadat abase. <TeamMember >Roel Gener</
TeamMember >
<TeamMember >JamesYounghusband</ TeamMember>
Anexampl eofahier
archychartisshowni nt hesli
de.Iti
sv erysimilar
<TeamMember >Phi
l Younghusband</TeamMember>
to or gani
zati
onalchar t
s.I trepresents a si mpli
fi
ed hi er
archical <TeamMember >JamesYounghusband</ TeamMember>
organizati
onofaschool.Therectangl
esr epresentt
hesegment s. </Footbal
lTeam>

SinceXMLi sapartofthemar kuplanguagef amil


y,t
hemar kuptakes
thef m oft
or agsencl
osedinanglebrackets,<>.Thesetagsareusedin
pairs,wit
h<tag>and</t
ag>delimiti
ngthebegi nni
ngandt heendofthe
portionofthedocumenttowhichthetagr ef
ers

XMLi sdisadv antageousi ntermsofdat ast or


ageascompar edtoa
rel
ati
onaldatabasebecauseXMLr epresentati
onisi neff
ici
entduet o
therepeti
ti
onoft agnamest hroughoutt hedocument .
I
n spite oft he di sadvant
age ment ioned,XML r epresentat
ion has
i
mpor tant adv antages when used t o exchange dat a bet
ween
organi
zati
ons,andf orstori
ngcompl exst r
ucturedinf or
mat i
onfiles.
Theseadv ant
agesar ethefoll
owing:

TagsmakeXMLmessagesel f-
documenti
ngsi
nceaschemamaynot
beneededtounderst
andt hemeaningofthetext
.Fragment
scan
readi
l
yber
eadevenbythosewhodon’tknowmuchabouti
t.

Thef ormatofXMLdocument si snotr i


gid.Theabilit
yt or ecognize
andi gnoreunexpect edt agsal l
owst hef ormatofdat at oev ol veover
ti
me,wi t
houtcancel li
ngexi sti
ngappl i
cati
ons.Likewise,theabi l
it
yof
AHi erarchicalPathi sanorderedsequencingofsegmentstraci
ngt he hav i
ng multiple occurrences oft he same t ag makes i teasy t o
hierarchi
calstructure.Anexampleoft hi
sistheoneshowni nthesl
ide. representmul ti
valuedat tri
butes.Forexampl e,i
fsomesenderadds
Theexampl etracksapat hfrom t
her ootsegmentt
o‘Par
tD’. i
nf ormati
onsuchasat agl ast_accessedwhi chdescribest hel astti
me
Thepat hintheexampl etr
acesallsegment sf
rom t
heroot,star
ti
ngat anaccountwasaccessed,t her ecipientoft heXMLdat amaysi mply
thel eft
mostsegment .This“l
eft-
li
st”pathisknownast hepr eorder i
gnor ethetag.
traversalorthehierarchi
calsequence. Awi devari
etyoft oolsar eavai l
abl etoassi stthepr ocessingoft he
XMLf ormat,incl
udi ngpr ogrammi ngl anguageAPI st ocreat eandt o
readXMLdat a,browsersof twar e,anddat abaset ool
s.

Businessesnowaday sar ei ntoe-commer ce.Thei nterneti snow an


essent ialpor talforallorganizati
ons.Tomakee- commer cepossi bl
e,
many di ff
erentsof t
warel anguages,sof twar
e pr oduct s,comput er
hardwar edev ices,andstandar dsexist.
Organi zat i
onssenddat af r
om t heirdatabasest ot hedat abasesof
CHAPTER3 otheror ganizations,andt hoseor ganizati
onst hatsenddat aneedt o
receivedat ainr et
urn.Inthesesi t
uations,t
hestructureandmeani ngof
XMLstandsforExtensibl
eMar kupLanguage.I
tisamar kuplanguage, thet r
ansmi tteddat aareofut mosti mpor t
ancebecauseor gani zati
ons
muchli
keHTML,buti twasdesi gnedt
ocarrydataandnott odisplay structuret heircommondat aintheirdatabasesindifferentway s.
dat
a.XMLt agsarenotpr edefi
ned.Youmustdef i
ney ourownt ags SinceHTMLi sunabl etospeci fythest r
uctureandmeani ngofdat a,
si
ncet
hesaidlanguagewasdesi gnedtobeself
-descr
ipt
ive. andaddr esst heneedf ortheexchangeofdat abetweenor ganizations,
XMLwasdev elopedandbecameaW3C( Wor l
dWi deWebConsor ti
um)
Page4of4
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

recommendat
ionin1998.W3C i
sthemai
nint
ernat
ionalst
andar
ds hasanat
tri
but
ecal
l
eddept
IDwi
tht
hev
aluedept
001.
organi
zat
ionf
ortheWor
ldWideWeb.
Att
r i
but
esarest r
ingswhichdoesn’tcontai
nmarkup.I
tcanonlyappear
AnXMLdocumenti sat r
eewhi chhasarootnodethatcont ai
ns oncei nagi v
ent agdeclarat
ioninstruct
st heXMLprocessortouse
vari
ouschi
ldnodes.Someofthesechi
l
dnodesar
ecall
edleafnodesor versi
on1.0oft heXMLspeci f
icat
ion.Theclausenexttot
hev er
sionis
chil
dnodeswithnochil
drenwhil
esomeofthem mayhav
echi l
drenof anopt i
onalone.Itspeci
fi
esthattheXMLdocumentusest heUnicode
thei
rown. charact
ercoding.

The<dat aroot>tagi dentifi


esanel ementnameddat arootwhi chi sa
 Root standardelementi nOf fice2007ex por
tedXMLdocument s.Dat aroot
Thisisal soknownast hedocumentnodewhi chist heabst r
actnode servesasacont ai
nerf oral ltheot herelement sdef i
nedint heXML
thatcont ainst heent i
reXMLdocument .Itencompassesal lot
her document ,and i ts mat ching </ datar
oot>t ag att he end oft he
element sint hedocument .Ithaschi ldrenwhi chi ncl
udecomment s, documentsi gnifi
est heendoft hescopeoft hedat arootel
ement .
processingi nst r
ucti
ons, andt herootel ementoft hedocument . Wi t
hintheopeni ng<dat aroot >tagandt hecl osing<dataroot>t agar e
 El ement( XMLel ement ) groupsofst atement s–onegr oupperrecordf rom thedatabaset able.
Thisissi mpl yapai rofmat chingst art-andend- t
agsandal lthetext Eachgr oupar eenclosedwi thint he<Student_tab>and</ Student _tab>
thatappear sbet weent hem.Thi sincludesanel ementname,asetof tags;those<St udent_ t
ab>t agsmar ksthebegi nningandendofeach
attr
ibutes,asetofi n-scopenamespaces, andal i
stofchi l
dren.
record.Also,eacht agpai rinsidethe<St udent_tab>tagscont ainst he
 Text
Thisreferst ot hepar sedchar acteroranyot herkindofnon- t
extnode fi
eldv al
uescal l
edel ementv al
uesf rom theStudent _t
abtable.Al ltags
enclosedbet weent wot ags. i
nanXMLdocumentmustal way shav eaclosingt ag.
 Comment
An XML commentsuch as<! -
-Thi si sa comment- -!>wherei ts Sohow doesanXMLpr ocessorunder st
andt hemeani ngoft het ags
contentsar eit sdata.Acommentdoesnothav eanychi ldren. andt hechar acteri
sti
csandst ructureoft hedat ainanXMLdocument ?
 Pr ocessingI nstruction Wel l,itcanei therbet hroughaDocumentTy peDef init
ion( DTD)oran
Apr ocessingi nstructionhasat argetandav al
ue.I tdoesnothav eany XMLschemat oprovidet hosei mpor tantf
actsaboutt hedata.
chil
dren.Forexampl e: DocumentTy pe Definition ( DTD)i s an optionalpar tofan XML
document . I t speci f
ies t he el ements ( t
ags),t he at tr
ibutes
<?
xml
-st
ylesheett
ype=”
text
/css”hr
ef=”
home.
css”?
> (char acteri
stics associ ated wi th each t ag), and t he el ement
relationshipf oranXMLdocument .DTDcanbeasepar atefil
ewi tha
XMLel ement smustbenest edpr oper ly
.Fori nstance: .dt dext ensionori fnot ,itcanal sobei ncl
udedatt hebegi nningofan
<cour se>..
.<t
itl
e>..
.</ ti
tle>. .
.</course> XMLdocument .
Tags ar e properl
ynest ed i feach oft he st art-t
ags has a unique Ont heot herhand,anXMLschemai sanewerf orm ofDTDt hatmor e
mat chingend- tagt hati si nt hecont extoft hesamepar entel ement. closel y mat ches database f eat
ur es and termi nol
ogy .Itcan be a
Also, not ethattextmaybemi xedwi tht hesubel ement sofanel ement. separ atef i
lewi than. xsdext ensi
onori fnot,itcanal sobeembedded
Forexampl e: att hebegi nningofanXMLdocument .
<Col lege-002> XMLdocument scontaindat a;andDTDsandXMLschemasdef i
net he
<depar tment> struct ur
e,char acter
istics,and r elati
onshi
ps of dat ai n an XML
<dept Name>I CT</ dept Name> document .
<dept Head>JuanaChange</ deptHead>
<inst ructor> Eachdecl arati
oni nt heexampl ei saf orm ofar egularexpr essionf or
<inst ructorI
D>002- 11</ inst ructorID>
thesubel ement sofanel ement.Theuni versit
yelementi nt heexampl e
<inst ructorName>Mar iaBant ay</instructorName>
consistsofoneormor ecourse,depar t
ment ,orinstruct orel ement s;
</inst ructor>
theoper atorr epresentedbyapi pesy mbol( |
)specifies“ or”whi l
et he
<inst ructor>
plussign( +)isanoper atorthatspeci fies“oneormor e.”Thekey word
<inst ructorI
D>002- 12</ inst ructorID>
<inst ructorName>JoseCr uz</instructorName> #PCDATA i ndicatest extdat aorsi mi l
art o str
ingdat at y pe,whi ch
</inst ructor> deri
vedi tsnamef r om “parsedchar acterdat a.

</depar tment > Othercomponent snotshowni nt heexampl eare:theast eri
sk( *
)isan
<depar tment> operatorwhi chisusedt ospecify“ zer
oormor e”,t
hequest i
onmar k(? )
<dept Name>HRM</ dept Name> i
sanoper atorwhi chisusedt ospeci fyanopt i
onalel ement( t
hati s,
<dept Head>St evenSmi t h</dept Head> “zer
oornone” ),#REQUI REDwhi chspeci fi
est hatav aluemustal way s
<inst ructor>
bepresentf oranat t
ri
bute,andmanyot her s
<inst ructorI
D>002- 25</ inst ructorID>
<inst ructorName>AnneAust i
n</instructorName>
</inst ructor> Thef
oll
owingnotati
onisusedwhenspeci fy
ingel
ement
s:
</depar tment >  Anast er i
sk(*)fol
l
owi ngtheelementnamemeansthatthe
</Col lege-002> elementcan be r epeat
ed zero or mor
et i
mes int he
The abi l
it
yt o nestel ement s wi t
hin ot herel ements prov i
des an document .Thiskindofel ementisknownasan opti
onal
alternat i
vewayt or epresenti nformat ion.Thegi venexampl eshows multi
valued(r
epeating)el
ement.
i
nf or mat i
onaboutacol legewi thdi f
ferentdepar tments.Thei nstr
uct
or
element sar enest edwi thi
ndepar t
mentel ement s.Nestingmakesi t  Aplussi
gn(+)foll
owingt
heelementnamemeanst hatthe
easyt oknowwhot hei nst ructorsar einaspeci ficdepartment. el
ementcanberepeat
edoneormor et
imesinthedocument.
Asi def rom thenodest hatXMLpossess, XMLal sospecifi
est henoti
on Thi
skindofelementi sarequi
redmult
ival
ued(repeati
ng)
ofat t
ributeswhi chappearasname=v aluepai rsbef oretheclosingofa el
ement
.
tag.Forexampl e:<depar tmentdept ID=”dept 001” >wher edepar t
ment
Page5of5
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

 Aquest i
onmark(?)foll
owingtheel
ementnamemeanst hat i
sUni v er sit
yType.Then,t het ypesofel ementsdepar tment,course,
theelementcanber epeat
edzerooroncei nthedocument
. i
nst ruct or,and t eaches wer e defined.Those el ementt ypes wer e
Thiskindisanopt
ionalsi
ngle-
val
ued(nonr
epeati
ng)el
ement. speci fi
edbyanel ementt agxs: element ,whosebodycont ai
nsthet ype
definition.
 Anelementwi
thoutanyoft
heprecedi
ngthr
eesymbolsmust Thet ypeofdepar tmenti sf urtherspeci f
iedtoconsistofasequenceof
appearonl
yoncei nthedocument.Thi
ski sar
ndi equi
red element ssuchasdept _name,bui l
ding,andbudget .Thi sshowst hat
si
ngl
e-val
ued(
nonr
epeat
ing)el
ement
. anyt ypet hathasei therat t
ributesornest edsubelementsarespecified
tobeacompl exty pe.
Anelement ’
stypei sspecifi
edusingpar ent
hesesfoll
owingt heelement. Also, not et hatelement scanbespeci fi
edt obeapr edefi
nedt y
pe.Not e
thatt he t ypes xs:st r
ing and xs: decimali nt he exampl e sett he
Ifthe parentheses include names ofot herelements,t hese l
atter
const raint sfordept _name, building,andbudget.
elementsaret hechi l
drenoft heel ementi nthetr
eest ructure.I
fthe
Finally,t het ypeUni v er
sityTy pewasdef i
nedascont ai
ningeit
herzer o
parent
hesesi ncludethe#PCDATAkey wordoroneoft hepr edefi
ned
ormor eoccur rencesofdepar tment ,course,i
nstructor
,andt eaches.
datatypesavailabl
einXMLDTD, thentheelementisaleafnode.
Theuseofr efist ospeci f
yt heoccur renceofanel ementdef i
ned
earli
er .
TheDTDexampl eabov ehighli
ght st heuse#I MPLI ED,ID,andI DREF.
#IMPLI ED meanst hatnodef aultv aluehasbeenpr ovided,andt he
XMLSchemaof f
erssev er
albenefit
sov erDTDsandthesearethe
documentmay omi tt his attr
ibute.Fori nst ance,when t he XML
fol
l
owing:
documenti sreadandi fanat tributehasadef aultvalue,forev ery
elementt hatdoesnotspeci f
yav al
uef ort heat tri
bute,thedef ault  I tal
l
owst hetextthatappearsi
nelement
stobeconst
rai
ned
valueisautomat i
callyfil
l
edin. tospeci
fict
ypes
Anat tri
butewithtypeI Dmeans“ auni queidentifi
erfortheel ement”.A
valuet hatcomeswi thanI Dat tributeofanel ementmayonl yoccur  I
tal
l
owsuser
-def
inedt
ypest
obecr
eat
ed
oncei nanyotherelementi nthesamedocument .
Anat tri
butewithtypeI DREFisar eferencet oanel ement .Theat t
ri
bute  I
tal
l
owsuni
quenessandf
orei
gn-
keyconst
rai
nts
musthav eavaluet hatappear sint heI Dat t
ributeofsomeel ementin
thedocument . I
tisi
ntegr
atedwi
thnamespacestoal
l
owdi
ff
erentpar
tsofadocument
TheDTDexampl eshowst heusageoft heabov ement i
onedkey wor ds. t
oconformtodif
fer
entschemas
Cour se,depar
tment ,andi nstr
uct orhav eident i
fiersrepresentedbyI D
attri
butes,and ther el
ati
onshipsbet ween them ar er epresented by XMLi swi
delyacceptedasadatarepr
esent
ati
onandexchangefor
mat
.
IDREFandI DREFS. Becauseofthi
s,softwaret
ool
sf orXMLdatamanipul
ati
onhavebeen
widel
yavai
labl
e.
DTDsar estronglyconnect edt othedocumentf ormat t
ingher i
tageof Therear
etwost andardmodel
sforprogr
ammat i
cmani
pulati
onofXML
XMLt hatiswhyt heyar enotsui tabl
ewheni tcomest oservingt he –DOM andSAX
needsofXML’ st ypest r
uctur efordata-processi
ngappl icati
ons.Her e
aresomeoft helimitati
onsofDTDsasaschemamechani sm: DOM ort heDocumentObj ectModeli sast andardAPI( appli
cat
ion
 I ndiv
idualt extel ements and at tr
ibutes cannotbe t y
ped programmi nginterf
ace)whichtreat
sXMLcont entasat r
ee,witheach
furt
her.Forex ampl e,oneel ementcannotber estri
ctedt o elementr epresented by a node cal
led DOMNode.Pr ograms may
haveonet ype.Thi sisproblemat i
cf ordatapr ocessi
ngand accesspar tsofthedocumenti nanavigat
ionalfashi
on,beginni
ngwith
exchangeappl i
cationssincet heyrequirecodet overif
yt he theroot.
typesofelement sandat t
ri
but es. DOM l i
brariesar eavai
lableinmostprogrammi nglanguagesandev en
i
nWebbr owser s,wheretheymaybeusedt omani pulat
ethedocument
 DTD mechanism is dif
fi
cultto use when speci
fyi
ng displ
ayedt ot heuser.
unor
der
edsetsofsubel
ements.
TheJav
aDOM APIprovidesthef ol
lowinginter
faces:
Ther
eisalackoftypinginI
DsandI
DREFSs.Becauseoft
his,t
her
eis Node
nowayt ospeci
fythetypeofel
ementt
owhi chanIDREForIDREFS El
ementandAtt
ri
bute(whichinheri
tsfrom Node)
at
tri
but
eshouldr
efer.  Node i nter
face – pr ovides met hods such as
get
Parent
Node( )
,get Fir
stChil
d(),and get Next
Sibl
i
ng(
),t
o
Duetothedefici
enciest
hattheDTDmechani sm has,theXMLschema nav
igatet
heDOM t ree,star
ti
ngwi ththerootnode
wasdeveloped.
XMLSchemadef i
nesanumberofbui l
t-
intypessuchasst r
ing,
int
eger
,  get
Element
sBy-
TagName(
name)– i
sused t
o accesst
he
subel
ementsofelementsbyname.Itr
eturnsal i
stofal
lchi
ld
deci
mals,date,andBoolean.Italsoall
ow user -
defi
nedtypeswhich
elementswit
haspeci fi
edt
agname;individualmember sof
may be simplet ypes wit
h added rest
ri
ctions,orcompl ex t
ypes theli
stcanbeaccessedbythemethoditem( i
)whichret
urns
const
ruct
orsusingconstr
uctor
ssuchascompl exTypeandsequence. theit
helementi
nt hel
ist

Thefir
stthi
ngtonoticeabouttheschemaisthatit
sdef initi
onsinXML  get
Att
ri
but
e(name)–i
susedt
oaccessat
tri
but
eval
uesofan
Schemaar ethemselvesspecifi
edinXMLsy nt
ax,usi ngav ariet
yof el
ementbyname
tagsdefi
nedbyXMLSchema.
Intheexample,theXMLschemat agsareprefi
xedwi th“ xs:
”t oavoi
d  Textnode–model
sthet
extv
alueofanel
ement
,whi
chi
sa
chi
ld ofthe elementnode;an elementnode wit
h no
confl
i
ctswithuser-
defi
nedtags.Thispr
efi
xisassociatedwi ththeXML
subel
ementshasonlyonechi
ldnode.Theget
Dat
a()method
Schemanamespacebyt hexml ns:
xsspeci
fi
cati
onint her ootelement: ontheTextnoderet
urnst
hetextcont
ents

Theex
ampl
eont
hesl
i
dehast
her
ootel
ementuni
ver
sit
y,whoset
ype  Al
so,DOM pr
ovi
desav
ari
etyoff
unct
ionsf
orupdat
ingt
he
Page6of6
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

documentbyaddi ng and delet


ing attri
bute and element Emp_I
D Emp_ Name EmpAddr ess Emp_
Age
chi
ldr
enofanode,sett
ingnodev alues,andsoon. 00001 Melanie Nov al
iches 27
 YoucanuseDOM t oaccessXMLdat astoredindat abases. 00002 Michael Cainta 26
Youcanalsouseitasapr i
mar yinter
facef oraccessingand 00003 Phoebe Mar i
ki
na 20
modif
yingdat
ainanXMLdat abase. 00004 Lomel Taguig 28

At upl ecorrespondst oar ow ofat abl eandanat tri


but eorf i
eldtoa
 SAX ort heSi mpl eAPIf orXMLi st hesecondcommonl y
column.Forexampl e,thesecondr owi ntheexampl ei nFi gur e4.1isa
usedpr ogrammi ngi nt
erfaceofXML.I tisanev entmodel ,
tuple.At uplei ssy nonymoust oar oworar ecor d.
designedt opr ov i
deacommoni nterfacebet weenpar sers
Ar elationiscomposedoff ields(attri
butes)andt upl es.Rel ati
onsare
andappl i
cations.I tisbuiltont henot ionofev enthandl ers,
stored as t ables inar elationaldat abase sy stem.At tri
but es ar
e
which consi stofuser -defined functions associ at
ed wi th
i
ndiv idualchar acteri
sti
cs,and t uples form t he unor der ed setof
parsingev ent s.Par singev entscorrespondt ot herecogni t
ion
char acter
isticst hatdescribeapar ti
cularentit
y .
ofpar tsofadocument ;forexampl e,anev entisgener ated
Apr imar ykeyi salsocal l
edamaj orkey .I
tisakeyf ieldthatser vesas
whent hest ar t
-tag isf ound foranel ement ,and anot her
theuni quei dent i
fi
erofaspeci fictupleinar elati
on.Gener all
yspeaki ng,
eventi sgener atedwhent heendt agi sfound.Thepi ecesof
i
tisaf iel
dwhi choccupi esthef i
rstcolumnwi thi
nacer t
ainr el at
ion.
adocumentar eal waysencount eredi nor derfrom st artto
Adomai nisapoolofl egalv aluesf oragi venat t
ribute.Forexampl e,
fi
nish.
 Gener all
y,SAXr equiresmor epr ogrammi ngef f
ortthanDOM, thedomai nf orEmp_ I
D mi ghtbeal istofuni que,f iv
e-di gitnumer i
c
buti thelpsav oidt heov erheadofcr eat i
ngaDOM t reei n codesassi gnedt oeveryempl oyee
sit
uat i
onswher et heappl i
cationneedst ocreateitsowndat a
representation.

CHAPTER4

E.
FCodd
I
tisimportanttonamear el
ati
onbasedonwhatv al
uesithol
ds.The
Thepr i
nciplesoft herelat
ionalmodelwereori
ginal
lyl
aiddownbyone rel
ati
on ortableisnamed Empl oyee si
nceitcont
ainsinf
ormati
on
man,Dr .E.F.Codd,att hatt i
meamemberoft heI BM SanJose aboutemployees(r
efertoFi
gure4.2).Theprimar
ykeyofthetabl
eis
ResearchLabor atory. theEmp_ID.EachEmp_IDuni
quelyident
ifi
eseachempl
oyee.
Itwasl ate1968t hatCodd,amat hemati
cianbytrai
ning,fi
rstreal
ized
thatthedi scipl
i
neoft hemat hemati
cscouldbeusedt oinjectsome Emp_I
D Emp_ Name Emp_ Address Emp_
Age
soli
dprinciplesandr i
gorintoafiel
d– 00001 Melanie Nov al
iches 27
00002 Michael Cainta 26
databasemanagement–t hatpriortot
hattime, wasalltoodefi
cientin 00003 Phoebe Mar i
ki
na 20
anysuchqualit
ies. 00004 Lomel Taguig 28
Codd’si deas weref i
rstwi del
y publi
shed in a classic paper ,“A
Relati
onalModelofDat aforLargeDataBanks” .Sincethatt
ime,t hose
i
deashav ehadawi de-r
angingef f
ectinf
luenceonj ustaboutev er
y I
tem_I
D I
tem_Name QTY
aspectofdatabasetechnology. 001 Shampoo 12
009 Soap 20
The relat
ionalmodelr epr
esentsthe database as a col
l
ect
ion of 003 El
ectr
icfan 5
rel
ati
ons,withrel
ati
onspert
aini
ngtotabl
eswi t
hrowsandcolumns. 008 Toot
hbrush 15
Eachrelati
onrepresent
sat abl
ewithvalues,ort
osomeext ent
,aflat For
eign
fi
leofrecords.
Emp_I
D I
tem_ID QTY
ARel at
ionalDat
abasei sat ypeofdat abasemanagementsystem t
hat 00001 001 6
storesinfor
mationint ables-
r owsandcol umnsofdat
a.Itconducts 00002 009 2
searchesbyusi ng datai nspeci fi
ed columnsofonet abl
et ofind 00003 003 1
additi
onaldatai
nanothert able. 00004 008 4
Ther owsofat abl
er epresentr ecor
dsandt hecol
umnsrepr
esentthe Abovetabl
esshowst hreedif
fer
entrel
atons:Empl
i oyee,I
tems,and
fi
elds. Sal
esSummary.Theprimarykeyofr
elat
ionEmployeei
sEmp_ I
D,whil
e

Page7of7
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

thepri
marykeyofrelatonI
i temsisIt
em_ I
D.Thesepri
marykeyscanbe CHAPTER5
usedtoli
nkanotherrel
ationwit
htherelat
iontowhi
chtheybelong.The SQL(
Str
uct
uredQuer
yLanguage)i
sadat
abasesubl
anguageusedi
n
pri
marykeyofanot hertabl
ethatisusedt odothi
sisref
err
edt oasa querying,updat ing,andmanagi ngr elati
onaldatabases.
for
eignkey. Itisder i
v ed f rom an I BM r esear ch group thatcr eated St ructured
Engli
shQuer yLanguage( SEQUEL)i nt he1970s.I tcanei t
herbeusedi n
formulatingi nteractiv
equer i
esorbeembeddedi nanappl icationas
Dat
aint
egr
it
yref
erst
othecompl
eteness,
accur
acy
,andconsi
stencyof
i
nstructionsf orhandl i
ngdat aandi sdesi gnedf orbot ht echnicaland
datai nt hedat abase.Forexampl e,i fanEmpl oy ee_ I
Di ssett o00001,
non-techni cal users.
thedat abaseshoul dnotal l
owanot herempl oy eet ohav eanI Dwi ththe
In1986,t heAmer icanNat i
onalStandar dsI nst
it
ut epubl ishedanSQL
samev alue.Meani ngEmpl oyee_ ID 00001i sdedi catedonl yt ot hat
standard.Al so,IBM publ isheditsowncor porateSQLst andar dwhi chis
empl oyee.Anot herexampl e,i fther el ationhasanAccessi on_ number
theSy stemsAr chitectureDatabaseI nt
erface(SAA- SQL) .
columnt hatst orest hebookaccessi onnumber ,thedat abaseshoul d
Asacomput erl anguage,SQLi smor eofadecl arati
v el anguage.A
all
owonl yv al
uest hatar ev alidfort hebookaccessi onnumberonl y.
Thepur poseofsuchr ulesi st oinf or mt heDBMSofcer tainlimi t
ations desir
edobj ecti nSQLi sof tendecl aredwi thsinglest atement .SQL’ s
i
nt her eal worldr epr esent edbyapar ti
cul ardat abase. simplest ruct urei spossi blesincei tisonl yconcer nedwi t
hr elati
onal
Mostdat abaseswi llbesubj ectt oav er yl argenumberofsuchi ntegrit
y databasesr at herthant heent i
retyofcomput ersystems.
rul
es.Fort heexampl egi venear lier
Herear esomepossi blei ntegrityr ules:  SQLcanexecut
equer
iesagai
nstadat
abase
 Emp_ I
Dmustbeauni quef i
v e-di gitnumer i
cnumberst arti
ng
f
rom 00001Emp_ Agemustbeaposi ti
v eintegerv alue  SQLcanr etrievedat af rom adat abase
 Emp_ NameandEmp_ Addr essshoul dnotbeempt y  SQLcani nser trecor dsi nadat abase
Therear etwot ypesofDat aI ntegr ityRul esandt hesear e;theSpeci fi
c  SQLcanupdat erecor dsi nadat abase
Int
egr i
tyRul es,whi char er ulest hatappl yt oapar ticulardat abaseand  SQLcandel et erecor dsf rom adat abase
theGener alIntegr ityRul es,whi char er ulest hatappl yt oallr elati
onal  SQLcancr eat enewdat abase
database.  SQLcancr eat enewt abl einadat abase
Inar elationaldat abase, wenev err ecor di nfor mat ionaboutsomet hing  SQLcancr eat est or edpr oceduresi nadatabase
we cannoti dent ify– t hi
s si mpl y descr bes whatEnt
i it
yI ntegrit
y  SQLcancr eat ev i
ewsi nadat abase
Const r
ai ntis.  SQLcansetper mi ssionont ables,procedures,andviews
Entit
yI ntegr i
tyConst r
ai ntisconcer nedwi t ht heconceptofapr imary Thef
oll
owingarethet hreemaj orcomponent sofSQL:
key.Iti sani ntegr ityr ulewhi chst at est hatev eryt ablemusthav ea  Dat aMani pul ati
onLanguage( DML) ,whichi samodul eof
theSQLl anguage, al l
owst heusert oretri
eve,update,add,or
pri
mar ykeyandt hatt hecol umnorcol umnschosent obet hepr imary
delet
edat ainadat abase.
keyshoul dbeuni queandnotnul l.  Dat aDef i
niti
onLanguage( DDL)enabl estheusert ocreate
Justifi
cat i
onsont heEnt ityIntegr ityConst raint : andmodi fythedat abasei tself
.
 Tupl eswi thinbaser elationscor respondst oent iti
esi nt he  Dat aCont rolLanguage( DCL)whi chmai ntai
nst hepr oper
r
ealwor ld.Forexampl e, baser elationEmpl oy eecor responds securi
tyforthedat abase.
t
oasetofempl oyeesi nt her eal wor l
d.
TRANSI STIONSTATEMENT:Adat abase,mostof ten,containsoneor
 Bydefini
ti
on,enti
ti
esinther
ealwor
ldar
edi
sti
ngui
shabl
e– mor etables.Each t ableisidentif
ied bycor responding name( e.g.
thati
stheyareident
if
iedi
nsomeway. “tbl
Students”,“ tbl
Customers”, and “tbl
Or ders”)
. Tabl es cont ai
ns
recordswithdat a.I
nt hi
ssub-t
opic,youwil
l belearninghowt oCREATE
 Ifanent i
tyi si mpor t
antenoughi nt her ealwor ldt or equir
e and DROP dat abase,and CREATE,ALTER,and DROP t ablei nthe
explici
trepr esent at i
oni nthedat abase,thent hatent itymust database.Statement swhichareusedt oadd, edit
,anddel eteat abl
ein
bedef i
nitelyandunambi guousl yi denti
f i
able.Ot herwi se,it adatabasewi l
lbediscussed.Beginbydefi
ni ngdatadef i
niti
on.
woul dev enbei mpossi blet otal kabouti tinanymanner . Data Definit
ion Languagest at
ement sallow y ou to mani pulatethe
 The Ref erent i
alI nt egri
t yConst raintisconcer nedwi ththe databaseitself
.Theyhav enothi
ngt odowitht hedat ainthedatabases.
conceptofaf or eignkey .Itst atest hatanyf oreignkeyv al
ue
can onl ybe i n one oft wo st ates.Thi smeanst hatt he TheCREATEDATABASEst atementisusedtocreat
eadat abase.To
database mustnotcont ain anyunmat ched f oreign key . cr
eate a database using t
his st
atement
,simplytype i
n CREATE
“Unmat chedf or ei gnkeyv alue”meani ng“ anon- nullf orei
gn DATABASE[ database_
name].Example:
keyv aluef orwhi cht her edoesnotexi stamat chingv alueof CREATEDATABASEdbEnr oll
ment;
thepr i
mar ykeyi nt het argetr elation”.
 Justaspr imar ykeyv aluesr epr esentent it
yi dent i
fiers,sodo TheDROP DATABASEstat
ementi
susedtodelet
eadat abase.To
foreign key v alues r epresent ent i
ty r efer ences. The del
eteadat
abase,t
hesynt
axisDROPDATABASE[dat
abase_name]
.
referenti
ali ntegr ityr ulesimpl yst atesthati fBr eferencesA, Exampl
e:
thenAmustex ist. DROPDATABASEDBEnr
oll
ment
;
 Not ethatr efer ent ialintegrit
yr equi resforeignkey st omat ch,
very speci fi
cal ly, pr imar y key s not al ternat e key s. TheCREATETABLEst atementall
owsy outocreatenew tabl
esi na
Furthermor e,f orei gnkeyandr eferenti
ali ntegr i
tyconcept s database.Example:
aredef inedi nt ermsofoneanot her.Iti snotpossi bleto CREATETABLEt blSt
udent
explainwhataf oreignkeyi swi thoutment ioningt hei deaof (student
NumberI NTPRIMARYKEY,
studentNameVARCHAR( 50)
,
referenti
ali ntegr ity,andl i
kewi sei tisnotpossi blet oexpl ai
n Cour seVARCHAR( 20))
;
whatr eferent iali ntegr i
tyiswi thoutment ioningt hei deaofa Thest atementabovewi l
lcr
eateat abl
enamedt bl
Studentwit
ht hree
foreignkey . fi
eldsnamelyStudentNumber,St
udentName,andCourse.Thephrase:

Page8of8
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

StudentNumber I NT PRI MARY KEY, wi l


l create a f i
eld name “
SELECTALLCOLUMNSFROM t
heEmpl
oyeet
abl
e”
StudentNumberasat abl
e’
spr i
mar ykeywit
hdataty pei
nteger.
Thenextphr aseistheSt udent
NameVARCHAR( 50)whichcr eatea Thestat
ement,SELECTEmployee_NameFROM tbl
Empl
oyeewi
l
lfi
nd
fi
eldnameSt udentNamei nav archardatat
ypewithamaxi mum l ength
al
lnamesoftheemployeesi
nthetblEmpl
oyeet
abl
e
ofcharacter
s.
Thel astphraseisCour seVARCHAR( 20)
,thi
scr eateaf i
eldnamed
Courseinav archardatatypewithamaxi mum l
engthof20char acters.

TheALTERTABLEst at
ementall
owsyoutomodifyspeci
fi
catt
ribut
es
ofthetabl
e.Forexample,t
oaddacolumninanexist
ingt
ableusethe Thestat
ement,SELECTDEPT,MGR FROM t blEmpl
oy eewi
llf
indall
syntaxbel
ow: managercodesandthei
rrespect
ivedepar
tmentsi
nt hetbl
Employ
ee
ALTERTABLEt bl
StudentADDSecti
onVARCHAR(10);
tabl
e.

ALTERTABLEt
blSt
udentDROPCOLUMNCour
se;

TheDROPTABLEstatemental
lowsyoutodel
eteatabl
einadatabase.
Usethef
oll
owi
ngsyntaxtodel
etet
blSt
udentt
ablei
nadatabase.
DROPTABLEtbl
Student
; TRANSI TIONSTATEMENT: “SQLcl ausesal soal lowt heuseofdi f
ferent
operator s,justl ikey ourmat h subject s,likeequalsi gn,l esst han,
greatert han,et c.t of i
ltert heneededi nf ormat i
on.Justl ikewheny ou
areor der i
ngameali nar est aurantorf oodchai n,yourselectedor ders
ThebasicSQLexpressi
onclausesar
e: arethei temsy ouwi l
lrecei ve.”
oSelect-usedtoli
sttheattri
but
esdesi
redi
nther
esul
tofaquer
y.I
t Basicoper atorsusedi nWHEREcl ausear e:
gi
vesyoutheabil
it
ytoretr
ievedatai
nSQL 1. =equal s
2. notequal
oFrom -li
stst
her
elat
ionst
obescannedi
ntheev
aluat
ionofan a. gr eatert han
ex
pressi
on 3. <l esst han
4. >=gr eaterthanorequal to
5. <=l esst hanorequal t
o
oWher e-consi stsofapr edi
cat einv
olvi
ngattri
butesoft
herelat
ions
thatappeari nthef rom clause Otheroper ators, suchast heBool eanoper ators, canalsobeusedwi th
At y
pi calSQLquer ylooksli
ket his: theWHEREcl ause.Theseoper atorsare:
SELECTA1, A2…AnFROM RnWHEREp; a) ANDoper ator–al lcondi ti
onsmustev al
uatetot r
uef ort he
wher e: rowt obesel ected
A1,A2…Anr epresent satt
ributes, b) OR oper ator– t he row wi llbe sel ected ifany oft he
Rnr epresentsrelations,and condi ti
onsi sdet erminedt obet rue
pisav al
idpredicat e c) NOToper ator–expr essesanegat ion, oranopposit e
Notet hat,keywor dsi nSQLar enotcasesensi t
ive.Thi
smeansthatthe d) BETWEEN oper at or– al l
ows y ou t o abbreviate an AND
wordSELECTi streatedident i
callyt
oselectorSelect
. expr essionwi thgr eaterthanorequal t o(>=)andlesst hanor
equalt o( <=)oper at
orsi ntoonesi mpl eexpressi
onwi tha
singleoper ator
e) I Noper ator–al lowsf oraspeci alcaseoft heORoper ator
Thegener alf ormatofaWHEREcl ausei ndicatest hatacondi tionmust
fol
lowt heWHEREkey wor d.
Thest atement ,SELECT Empl oy ee_Name,DEPT FROM t blEmpl oyee
WHERESal ary=15000wi lldisplayal lempl oy eeswhosesal ariesar e
equal to15000.

thetblEmpl oyeeconsi sti


ngof5f i
elds:theEmpl oyee_I
Dwhi chi
sthe
pri
mar ykeyt hathol dstheempl oyeeI D;Empl oyee_Namei sthename
oftheempl oyee;MGRr eferstothecodeassi gnedt othemanagerof
theempl oyee;DEPT i st hedepar t
mentunderwhi cht heempl oy
ee The nextexampl
e,t
he st
atement
,SELECT Employ
ee_Name FROM
bel
ongs;and Sal ar
yr ef
er stot he mont hly compensat i
on ofthe tbl
EmpoyeeWHEREDEPT=‘Syst
em’di
spl
aysallempl
oyeesinSyst
em
employ ee. depar
tment.
The stat ement ,SELECT *FROM t blEmployee wi l
ldi spl
ay al
lthe
contentsoft blEmployeet abl
e.Theast er
isk( *)isaspeci alsy
mbol
whichmeans“ allcol
umns” .Whensimpl ystated,thestatementmeans:
Page9of9
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

pr
oducest
hesameout
put
.

TheSt atement,SELECTEmpl oy ee_NameFROM t bl


EmployeeWHERE
DEPT=‘ Sal
es’ANDMGR=12125wi l
lonl
ydispl
ayemployeeswhoare Thefol
lowingar etheaggregat efunct i
onsi nSQL:
from thesalesdepartmentandwi thmanagercodeof12125.Not i
ce  SUM – t hi
s key word wi lladd t he v alues ofa speci f
ied
thatRey esdidnotappearinther esul
tbecausethestat
ementusethe column.For mat:SUM<col umnname>
AND oper atori
naWHEREcl ause.Meaningbot hexpr
essionswhen  AVG–t hiskeywor dwi ll
findt heav erageofal lthevaluesi
na
ev al
uatedmustresul
ttotrue. specifi
edcolumn.For mat :AVG<col umnname>
 MI N–t hiswil
lfindt helowestv aluei nthespeci fi
edcolumn.
Format :MIN<columnname>
 MAX–t hi
swillf
indt hehi ghestv alueint hespecifi
edcolumn.
Format :MAX<col umnname>
 COUNT–t hiswi l
lcountt henumberofr ecords( r
ows)ina
Another exampl e, t he st atement, SELECT Empl oy ee_ID, column.For mat:COUNT<col umnname>
Employ ee_Name,SalaryFROM t bl
EmployeeWHERE Employ ee_ID> SELECTDI STINCTDEPTFROM t bl
Empl oy
ee;
1003OREmpl oy
ee_I
D<1002wi lldi
spl
ayemployeeswit
hEmpl oyee_ID Thestatementabov ewilldi splayt henameoft hedepar tmentonly
greaterthan1003orlessthan1002.Al
lemployeeswhoseemploy eeID oncethought herearesever alinstancesofsi mil
ardepar tmentnames
thatsatisfi
eseit
herofthecondi
ti
onwhenev al
uatedwil
lbetheout put. i
nthetable.
Seeresul tbel
ow:

SELECTSUM( Salar
y)asSumSalaryFROM tblEmployee;
SELECTAVG( Sal
ary)asAVGSalaryFROM tblEmpl
oy ee;
Thef i
rststatementabov ewil
ladd allthev al
uesi nt hespeci
fi
ed
SELECT Empl oyee_I
D,Empl oy
ee_Name FROM tbl
Employee WHERE
col
umn( whichisSalary)andputittoSumSal ar
yf iel
d.Seeresul
ton
DEPT<>' Sal
es';
Thestatementabov edispl
aysallemploy
eeswhodon’tbelongt
othe Table5.15.Thesecondst at
ementwill
findtheaverageofallt
heval
ues
Sal
esdepar tment.TheNOToper at
orisal
soequi
val
entto<>operat
or. i
nt hespecifi
edcolumn( whichisSal
ary)andputitt oAVGSalar
yfi
eld.
Theresultofthestat
ementaboveis: Refert
oTabl e5.16fortheresul
t.

SELECTMI N(Salary)asMi nSalaryFROM tbl


Employee;
SELECTMAX( Salar
y )asMaxSal aryFROM tbl
Employee;
SELECT Empl oyee_I
D,Employee_Name,Salar
y FROM t bl
Employee Thefir
ststat
ementabov ewilldispl
aytheSalar
ywiththelowestval
ue,
WHERESal ar
yBETWEEN15000AND25000; whil
et hesecondst atementwi l
ldispl
aytheSalarywiththehighest
Or val
ue.
SELECT Empl oyee_I
D,Employee_Name,Salar
y FROM t bl
Employee
SELECT COUNT( Employee_ Name) as Empl oyeeCount FROM
WHERESal ar
y>=15000ANDSal ar
y<=25000;
Thet wostat
ement sabovepr
oducet hesameoutput.Thest
atements tbl
Employee;
di
splayemploy eeswithsal
ari
esrangingfrom 15000to25000.See DML–Dat aMani pulati
onLanguage
outputbel
ow.  SELECT-ext
ract
sdat
afr
om adat
abase
 UPDATE-updat
esdat
ainadat
abase
 DELETE-del
etesdat
afr
om adat
abase
 INSERTINTO-inser
tsnewdat
aint
oadat
abase
DDL–Dat
aDefini
ti
onLanguage
 CREATEDATABASE-cr
eat
esanewdat
abase
 ALTERDATABASE-modi
fi
esadat
abase
SELECT Employee_I
D,Employee_Name,Salary FROM tbl
Employee  CREATETABLE-cr
eat
esanewt
abl
e
WHERESalary=11000ORSalary=25000orSalar
y=30000;
SELECT Employee_I
D,Employee_Name,Salary FROM tbl
Employee
 ALTERTABLE-modi
fi
esat
abl
e
WHERESalaryIN(11000,
25000,30000)
;  DROPTABLE-del
etesat
abl
e
Thefir
stst
atementabovewilldi
splayt
heempl oyeeswhosesal
aryis  CREATEI
NDEX-cr
eat
esani
ndex(
sear
chkey
)
equalto11000,or25000,or30000.Thesecondst atementabove  DROPI
NDEX-del
etesani
ndex

Page10of10
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

CHAPTER6 UPDATEst
atementi
susedbef
oreexpl
aini
ngt
heexampl
e.
Ther
ear ethreebasicscenar
iosastohow dat
ainat
abl
ecanbe
modif
ied: The SQL UPDATE st atementallows to updat e exi
sti
ng dataina
 I nsert
ingnewrowsintoat
abl
e, database.
Here’sthesy ntax:
 del
eti
ngr
owsf
rom at
abl
e,and UPDATE t able_name SET column1 = v alue1,col umn2 = value2,…
WHEREcondi ti
ons;
 updat i
ngexistingdat ainspecifi
cr owsandcol umnsi na Assumi ng thatwe wantt o updatethe r ecord ofMel ani
e Rey es
table. repl
acingherCour seCodewithBSN.Uset hef ol
lowingSQLstatement :
Themechani csofmodi f
y i
ngdataar efai
rl
yst r
aightf
orwar d.Howev er, UPDATEt blStudentSETCourseCode=‘ BSN’ WHERESt udent
Number=

1003’;
updat i
ngexistingdatai smor ecompl ex.I
nt hissub-topic,wewi llbe
focusingonhowt oinsert,del
ete,andupdatedataofat ablei natable.
Thet hreecommonst atementsusedi nSQLwhenmodi fy
ingdat aare:
 I NSERTI NTO-enabl esy outoadddat aint
oat able

 UPDATE-i
susedt
oedi
tdat
ainat
abl
e

 DELETE-i susedt ohandl edeletes;delet


esent ir
erows
SQLI NSERTI NTO
TheI NSERTI NTO st atementcanbewr it
teni ntwof orms.Thef i
rst TheSQLDELETEst atementall
owst odelet
erowsinatable.TheSQL
form doesnotspeci f ythecol umnnames,onl ythei
rv al
ues,andthe DELETEsyntaxi
s:
secondonespeci f
iesbot ht hecol umnnamesandt hev al
uest obe DELETEFROM tabl
e_nameWHEREcondi ti
ons;
i
nser ted.Herear ethesy ntaxes: Assuming we wantt o del
etethe studentwho has 1000 as hi
s
INSERTI NTOt able_nameVALUES( val
ue1, val
ue2,val
ue3, …); Student
Numberf r
om t he t
abl
et bl
Student.Use t
he f
oll
owing SQL
INSERT I NTO t able_ name ( col umn1,col umn2,col umn3, …)VALUES st
atement:
(value1,value2,value3,…) ;
DELETEFROM tbl
StudentWHERESt udentNumber='
1000'
;
Ther earetwobasi cway sonhowt odoi tandt heseare:
1.inserti
ngspeci ficdat athati slist
edinanI NSERTst at ement,and

2.i
nser
ti
ngdat
athati
sobt
ainedf
rom aSELECTst
atement
.

Thet ableabov eshowst hest udenti nf ormat i


onwi thSt udent Number Not i
cet hatt hest udentwhohas1000ashi sSt udentNumberwas
as it
s pr i
marykey .Assumi ng thatt he St udentNumbercol umn i s deleted.
defi
nedasanaut o-incrementcol umnwhi chmeanst hatwhenar owis Not i
cet heWHEREcl ausei ntheSQLDELETEst atement,itspecifi
es
addedt othetblStudentt able,thereisnoneedt ospecifyav al ueforthe whichr ecordt obeupdat ed.Ifyour emov et heWHEREcl ause,all
StudentNumbercol umnsi nceitwillbeaut omat i
call
ygener at ed. recordswi l
lbedel eted.
Ifyouwantt oaddt wonew st udent st ot het abletblStudent :Mel ani
e Todel eteal lrecor dsi nat ablewi t
houtdel et
ingt het abl
e,uset hi
s
Reyeswho i st akingupBachel orofSci encei nComput erSci ence statement :
(BSCS)andCeci l
leBer maswhoi st akingupBachel orofSci encei n DELETEFROM t able_ name;
Education(BSED) ,SQLst at ementshoul dbe: Or
INSERTI NTOt blStudent( LastName, FirstName, CourseCode) DELETE*FROM t able_name;
VALUES( '
Reyes','Mel ani
e','BSCS','Bermas' ,'
Cecil
le'
,'BSED' );Af t
erthe Assumet hatthet ablet blProductwasal r
eadycr eatedinadbI nventory
:
executi
onoft hest atementabov e,t het abl
ewi l
llookl iket heone  St or ethef oll
owi ngrecordsintblProduct:
shownbel ow. ProductI
D Name Brand Price
P0001 Head and Pr octer and 5. 00
Shoul der Gambl e
P0002 Knor r Unili
ver 1.00
P0003 Dat uPut i Nut r
iAsi
a 7.00
P0004 Rexona Unili
ver 10.00
 Updat et hepr iceofKnor rproduct.

 Addanewr ecor
dwhichhasProductI
DP1009asit
sproduct
i
d,Tobl
eroneasitsname,US-
Amer i
canasi
tsbr
and,andits
INSERTINTOtblStudent pr
icei
s450.00.
VALUES(‘Gagari
n’
, ‘
Ria’,
‘BSHRM’)
ThisexampleofI NSERTI NTO st
atementomitstheincl
usionofthe  Updat
et he Tobler
one’
s br
and t
o US-Amer
ican Mondel
ēz
columnnamesandst at
et heval
uesdir
ectl
y.Justmakesur ethatt
he I
nter
nati
onal
,Inc.andit
snewpri
ceof360.
00
val
uesarechronologi
callyinor
derwitht
hecolumnsinthetable.
UPDATESt
atement  Del
eteP0003.
1.Cont
inuet
hedi
scussi
onbypr
esent
ingSl
i
de5.Di
scusshowt
heSQL
Page11of11
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

CHAPTER7
Beforel
earninghow t ocreat
ey ourownv i
ewsinSQL,y oumustf i
rst
l
earnthejoinclauses.
You can retri
eve and displ
ay data ofa t abl
e using t
he SELECT
stat
ement.Butwhent her
eisaneedt odispl
aydatafrom t
woormor e
tabl
es,otherkey wordsar e combined withthe SELECT st
atement.
Thesekeywor dsare: i
nbotht ables.
 I NNERJOI N Thebasicsy ntaxofI NNERJOI Nar easfol
lows:
SELECTt able1.column1,table2.column2..
.
FROM table1
 OUTERJOIN
I
NNERJOI Nt able2
 LEFTJOI
N
ONtable1.common_ fiel
d=t able2.common_ fi
eld;
And
 RI
GHTJOI
N SELECT*FROM t abl
e1
I
NNERJOI Nt able2
 FULLJOI N ONtable1.common_ fiel
d=t able2.common_ fi
eld;
AnSQLJOI N clauseisusedt ocombinerecordsfr
om twoormor e
tabl
esi
nadat abase,basedonacommonf i
eldbet
weent hem.Asan
exampl
e,wehav etwotablesbel
ow,thefi
rstt
ablehol
dsther ecor
dsof
cust
omerdet
ailsandthesecondtabl
eisforcustomer’
sordersdetai
l
s.

SELECT tblCustomer.
CustomerI
D, tbl
Cust
omer
.Name,
tbl
Customer.
Address,tbl
Order
s.Amount
FROM tbl
Customer
I
NNERJOI NtblOrders
ONt bl
Cust
omer .
Customer I
D=t bl
Order
s.Cust
omer
ID;

Combini
ngthesetwot
abl
esusi
ngt
heSQLJOI
Ncl
ausewoul
dpr
oduce
thef
oll
owingresul
t

SELECT*
FROM tbl
Cust
omer
I
NNERJOI Ntbl
Order
s
ONtblCust
omer.
Customer
ID=t
blOr
der
s.Cust
omer
ID;

Joi
npr oducestheresul
thav i
ngthecommonf i
eld(
outli
nedinr ed)
betweenthetwotabl
es.TheCustomer
IDcolumninthetabletbl
Orders
ref
erst o the CustomerI
D in the t
blCustomer t
able,in whi ch
CustomerI
Dcolumnisthei
rcommoncolumn.
TheINNERJOI Nkeywordret
urnrowswhentherei
satleastonemat ch
Since I
NNER JOI Nr equi
resatl
easttwo tablesto have matchi
ng
columns,thepri
mar ykeyofonetabl
emusthav eamat chi
ngforei
gn
keytot heothertabl
et ocombi
newith.Wit
ht heexampl eabov
e,the
columnconnect i
ngt hetwotabl
esist heCust omer
ID whichisthe

Page12of12
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

pri
marykeyoft blCustomerandt heforei
gnkeyonthet blOrders. t
blGenr
etabl
ewi
tht
heGenr
eIDandGenr
eDesccol
umns.
AnOUTERJOI Ni sanext ensionofI NNERJOIN.Butitdoesnotr equire
eachrecordint hetwoj oi
nedt ablestohav eamat chingr ecord.The
j
oinedt abl
er etai
nseachr ecord—ev enifnoot hermat chingr ecord
exi
sts.Outerjoinssubdi videf ur t
herintol
eftouterjoins,r i
ghtout er
j
oins,andfullouterjoins,dependi ngonwhi chtabl
e(s)oner etai
nst he
rowsfrom (l
eft,
r i
ght
, orboth).

TheLEFTJOIN key
wor
dr et
urnsal
lrowsfr
om t
hel
eftt
abl
e(t
abl
e1)
,
eveni
fther
ear
enomatchesinther
ightt
abl
e

TheRIGHTJOIN keywor
dret
urnsallther
owsf r
om therightt
abl
e
(t
abl
e2),
eveni
fther
earenomatchesi
nthel
eftt
abl
e(t
able1)
.

I
nt heFULLJOI N,bot ht
ablesar esecondar y(oropti
onal),suchthati
f
rowsar ebeingmat chedintableAandt abl
eB, t
henallrowsf r
om tabl
e
Aar edi spl
ayedev enifthereisnomat chingr ow i
nt abl
eB,andv i
ce
versa.
SELECT tblCust
omer .
Customer I
D, t
blCustomer .
Name,
tbl
Cust omer.Address, tbl
Customer .
Salary, t
bl Or
ders.Amount,
tbl
Or ders.
Date
FROM t blCustomer
LEFTJOI NtblOr
ders
ONt blCustomer.CustomerID=t bl
Orders.CustomerID

Thestat
ementbel ow il
lustrateshow theFULLJOI N keywor
dwor ks.
TheSELECT clausewillonl ydi spl
aytheMov i
eTit
leand Genr
eDesc
col
umns.
SELECTtbl
mov i
e.Movieti
tle,tblGenr
e.GenreDescFROM t
blMovi
e
FULLJOINtblGenre
ONtblMovi
e.GenreCode=t bl
Genr e.
GenreCode

Thet ableabov e,displayal lther ecordsf r


om t hetwot ables(tbl
Orders
andt blCust omer )ev enifsomer ecordfrom onet abledoesn’ thavea
matchingdat aont heot hert able.Thi sresulttoimpar t
ingcustomer s
Feli
cidad,Rogel io,andAgust i
not ot her esult
ingtableev enift hey
doesn’thav eanor dertransact ionr ecord.IfweuseanI NNERJOI N
keywor di nstead ofaLEFT JOI N,Fel i
cidad,Rogelio,and Agust ino
wouldn’tbeapar toft heresul ti
ngt able.
SELECT tblCustomer .Cust omer I
D, t
blCust omer.
Name,
tbl
Cust omer .
Addr ess, tblCust omer .
Salary, t
blOr der
s.Amount ,
tbl
Order s.
Dat e
FROM t blCust omer Obser vethatt herearetwoblankcell
si ntheresul
tingtabl
e,whichisa
RIGHTJOI Nt blOr ders dir
ectr esultofusi ngaFULLJOI N.Shr ek hasaNULLGenr eDesc
ONt blCust omer .
Cust omer ID=t blOrders.
Cust omerID becauset herewasnov alueforGenreCodeint het bl
Genrestabl
ef or
thatmov i
e.Al so,thereisnomov i
et hathasSci -
figenreasseeni n
tbl
Mov ie,resultingt
oNULLmov i
et i
tl
e.
Fulljoi
nisr arelyusedbecausethistypeofrel
ationshipbet
weent abl
es
i
sr elat
ivelyuncommon.Thi skeywordshowsdat awher ether
ear eno
mat chesinbot hdir
ecti
onsbetweentables.

CHAPTER8
Accor di
ngtoLarryRockoff,v
iewsareSELECTst atement sthathave
TheRIGHTJOI Nkey wordhasani denti
calconceptwit
htheLEFTJOI N beensav edi nt
hedatabase.Oncesaved,theview canber efer
redto
keyword.Theonl ydiff
erenceist heor derofthetwotablesinthejoi
n the same as anyt abl
ei nthe dat
abase.Dat abase tables contai
n
areli
sted.I
nRI GHTJOI NS,thepr i
mar ytabl
eislist
edtotherightoft
he physicaldatawhi
lev
iewsdonotcontaindata,butall
owy outoproceed
RIGHTJOI Nkey word.Assumet hatt hefoll
owingtabl
esar efrom t
he asifthev i
ewwasar ealt
ablewit
hdata.
Mov i
es database.The f ir
stt ablei s named as tbl
Mov i
e wi t
hthe Youmaybewonder i
nghowv i
ewsarestoredinadat abase.Viewsare
Mov i
eID,Mov i
eTit
le,andGenr eIDcol umns,andt heothertableist
he creat
edusi ngtheCREATEVI EW keyword.Itenablesuser stocr eat
e

Page13of13
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

newv iews.Bel owi sthebasi csy ntax: dat


abasecontai
ningcolumnnamesthatar
ecomplex,you
CREATEVI EW v i
ewNameAS maycreat
evi
ewswi thcolumnal
i
asest
omakethosecol
umn
SELECTst at ement namessimpl
er.
wher ev i
ewNamei susedasar eferencet ot hedat athatwouldbe
returnedf rom t hest atementt hatcomeswi ththeSELECTcl auseinthe  Viewscancr eatesubsetofdat a.Fori nstance,ify ouhav ea
view. tablecont ainingal lt hest udentsi naschool .Mostoft he
Assumet hatt het hreet abl
esont heslidear ef rom theDBEmployee userswi l
lonl yneedt heact iveort heon- goingst udents.You
dat abase.Thef irsttabl
ei stblEmpl oyeet able,thesecondt abl
eisthe caneasi l
ycr eat eav iewt hathast hisusef ulsubsetofdat a.
tblLogRecor dst able,andt hethirdonei sthet blTimeRecordstabl
e.  Vi ewscanbeusedt oenf orcesecur i
tyr estri
ctions.I fyou
wantuser st oaccessonl ycer taincol umnsi nat able,you
SELECT
cancr eat eav iewoft het ablef ort hoseuser s.Then, youcan
tblEmpl oyee. EmpNameAS‘ Name’ ,
uset hesecur ityfeat uresofy ourdat abaset ograntaccesst o
tblLogRecor ds. LogDat eAS‘ Date’ ,
thenew v iew f ort hoseuser swhi ler estr
icti
ngt hem f r
om
tblTimeRecor ds. TI nAS‘ TimeIn’,
tblTimeRecor ds. TOut AS‘ TimeOut ’ accessi ngt heor i
ginal table.
FROM t bl
Empl oy ee Afterav i
ewhasbeencr eated,y oucanal teri tusingt heALTERVI EW
LEFTJOI Nt bl LogRecor ds statement.Itssynt axi s:
ONt bl
Empl oy ee. Empl oyeeID=t blLogRecor ds.Empl oy
eeID ALTERVI EW v i
ewNameAS
LEFTJOI Nt bl TimeRecor ds SELECTst atement
ONt bl
LogRecor ds.LogID=t blTimeRecor ds.LogI D When al t
ering a v i
ew,y ou need t o speci fythe compl et e SELECT
CREATEVI EW Empl oyeeTimeSheet Vi
ewAS statementcont ainedi nt hev i
ew.Theor i
ginalSELECTi nthev i
ewget s
SELECT replacedbyt henewSELECTt haty ouspeci f y.
tblEmpl oyee. EmpNameAS‘ Name’ ,
tblLogRecor ds. LogDat eAS‘ Date’ , ALTERVI EW exampl e.
tblTimeRecor ds. TI nAS‘ TimeIn’, Student No FName MName LName
tblTimeRecor ds. TOut AS‘ TimeOut ’ 001 Jane Sant os Aqui no
FROM t bl
Empl oy ee
002 Mar k Guzman Per ez
LEFTJOI Nt bl LogRecor ds
003 Leo Mar quez Pacqui ao
ONt bl
Empl oy ee. Empl oyeeID=t blLogRecor ds.Empl oy
eeID
LEFTJOI Nt bl TimeRecor ds Assumet hatt het able8. 1isnamedast blStudentInfowi t
hcol umns
ONt bl
LogRecor ds.LogID=t blTimeRecor ds.LogI D suchasSt udent No, FName, MName, andLName.
Then, wecr eateav i
ewoft hetbl Student I
nfot ableusi ngt hest atement
Thef
oll
owingar ethebenef i
tsofViews: ont hesl i
de.Af tert hest atementont hesl i
dehasbeenexecut ed,t he
 Vi ewscanr educecompl exit
y.Byt his,SELECTst at
ement s tablei l
lustratedont hesl idewi l
lbeav iewoft hetblSt udentI
nf ot able.
thatar ecompl excanbesi mplif
ied.Forexample,ifyouhav e Thatv i
ewi snamedt heStudent sVi ew.
aSELECTst atementwi t
hsi xtablestojoi
ntogether,y
oumay Then,t hest atementshownont hesl i
dewi llmodi fyt hev i
ew cr eated
createt wo v i
ewswi tht hreetableseach.Then,y oumay
from Sl ide11.Thatst atementwi lladdanew col umn( whichi st he
referencethev i
ewsy ouhav ecreatedusingasimpl eSELECT
statementt hatisl esscompl exthanaSELECTst at
ementf or mi ddlename)t ot heSt udentsView
sixseparatet ables. Remembert hatcr eat i
ngoral teringav iewdoesnotr eturnanydat a.It
onlycr eatesormodi fiesthedef initionoft hev i
ew.
 Viewscan i ncreaser eusabi
li
ty.Ifyou hav esituati
onsof Asi def rom modi fy i
ngv i
ews,y oumayal so del etev iewsusi ngt he
tablesbeingj oinedtogetherfrequentl
y ,youcancr eatea DROPVI EW key wor d.I t
ssy ntaxis:
view ofthoset ablessoast oav oi
djoiningthem repeatedl
y DROPVI EW Vi ewName
ev er
ytimey ouneeddat afrom thosetables.Withviews,you Fori nstance,i fy ouwantt odel et et heSt udent sViewt hatwascr eated
j
ustsi mplyhavet oref
erencethepredefinedview. ear l
ier,thestatementwoul dbe:
DROPVI EW St udent sView
 Viewscanpr oper l
yf ormatdat a.Vi ewscanbeusedi fy ou CHAPTER9
hav e a column t hati s notf ormat t
ed cor rectl
yi ny our  Aut horizat iont oreaddat a
databasebyusi ngfunct ionst of ormatt hespeci f
iedcol umn  Aut horizat iont oinsertnewdat a
exact l
yhowy ouwanti t.Fori nstance,ify ouhav eacol umn
containingdateswi tht heYYYYMMDDt hati sstoredasan  Aut
hor
izat
iont
oupdat
edat
a
i
ntegert ype and y ou wantuser st ov iew t hi
s dat a as
data/ t
imecolumn,y oumaycr eat eav iewwhi cht ransforms
thatcol umntot hepr operf ormat .Af t
erdoi ngso,y oumay  Aut hori
zati
ontodelet
edat a
reference tot he created v iew hav ing t he cor r
ectf ormat Eachoft het ypesoft heaut
horizati
onli
stsiscaledapr
l i
vil
ege.You
ratherthanreferencingtot het ableitself. mayaut horizet heuserwi t
h all,none,ora combinati
on ofthese
pri
vil
egesonspeci fi
edpart
sofadat abase,suchasarel
ati
onorv i
ew.
Sof orexampl e,ifausersubmi tsaquer y,theSQLimplementati
on
 Viewscancr eatecalculat
edcol umns.Forexampl e,ifyou checksf i
rstifthequer yi
saut hori
zed.SQLchecksi tbasedont he
havecol umnssuchasTui tionFeeandMi scFee,andy our authori
zati
onst hattheuserhasbeengr anted.I
fthequer yisnot
usersalwaysl ooksattheTot alFeedatawhichisequival
ent authori
zed,i
tisreject
ed.
toTuiti
onFeepl usMi scFee,theny oucancreateav iew f
or
thecalculat
edTot al
Feesot hatuser scanreferencetothat Pri
vil
eges thatthe SQL standardi ncludes are SELECT,INSERT,
viewthatisalwaysreadil
yav ailable.
UPDATE, andDELETE.Theallpri
vi
legespr iv
il
egeisashor tf
ormforal
l
theall
owablepriv
il
eges.Auserwhocr eatesanewr elat
ionortabl
eis
 Vi
ewscanbeusedt
orenamecol
umnnames.I
fyouhav
ea
automati
call
ygrantedwit
hal
l t
heprivi
legesont hatr
elati
on.
Page14of14
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

 object
_namei
sthenameofadat abaseobj
ectl
i
keTABLE,
Todothis,DCLcommandsareused.TwotypesofDCLcommandsare VIEW,STOREDPROCandSEQUENCE
theGRANTandREVOKEcommand.
Herear
et heaut
hor
izat
ionst
hatmaybegrantedorr
evokedt
oauser
:  user
_namei st
henameoft
heuserf
rom whom ar
ighti
s
bei
ngdisal
l
owed
TheSELECTaut hori
zati
ononat abl eorr elati
onsi sr equiredt or ead
rowsi nt het able.  r
ole_nameorr olesareasetofdisall
owedpri
vi
legesgr ouped
TheUPDATEaut hori
zationonat ableal lowsausert omodi fyanyr ow t
ogether
i
nat abl e.Itmaybegi venei t
heronal lthecol umnsoft het ableoron Sampl e1:
onlysome.I fanupdat eaut horizat i
oni swi thagr antst atement ,the REVOKESELECTONSt udent I
nfo
column/ swhi cht heuser sar egr ant edaccesswi thi sst at edi nside FROM Juanito
parent hesesaf tertheupdat ekey wor d.Ot herwise,i fthecol umn/ sar e Sampl e2:
notspeci f
ied,theuserwi l
lbegr antedupdat epr i
vil
egesonal lt he REVOKEUPDATE( Student No)
columnsoft hespeci fi
edt abl e.Samewi tht her evokest atement ,only ONSt udentI
nfo
thatthepr i
v i
legei sdisal
lowed. FROM Juanito,Juanita
Fort heI NSERTaut hori
zat i
on, ifgr antedt oauser ,
t hisal l
owst hatuser TheREVOKEcommand( sample1)wi l
ldi
sallowJuani
tofrom selecti
ng
toi nser trow/ si naspeci fiedt able.I nt hi
saut hor i
zat i
on,al istof records fr
om t he tblStudentI
nfo tabl
e. The REVOKE command
columnsmaybespeci fi
ed; anyi nser tsmustbespeci f
iedonl yf orthose (example 2)wi llrestr
ictJuani t
o and Juanitofrom modifying the
columns,and t he system wi l
lei t
hergi ve defaul tv alues f ort he StudentNocolumnf rom t hetbl
Student
Inf
ot abl
e.
remai ningcol umnst hatwer enotspeci fi
edorsett hem t oanul lvalue.
Lastly,theDELETEaut hor i
zationwi llallowausert odel etear owf rom Hav ingaquer yinsideanot herquer yispossi bl
e.Thesequer iest hatare
aspeci fiedt able.I fauseri sr ev okedoft hi
spr ivi
lege,t heuseri s cont ainedwi t hi
not herquer i
esar ecalledsubquer i
es.
Ther ear emanyway sinwhi chsubquer i
escanbeused.Subquer iescan
disall
owedt odel eterow/ s.
bef oundi ndi f
ferentpartsofSELECTst atements,eachwi thdi ffer
ent
distincti
ons and r equir
ement s. Also,subquer ies can ei ther be
The GRANT command i s a command used t o provi
de access or dependentt o ori ndependentf rom t he mai n query.Agai n,t hi
s
pri
vi
legesont hedat abaseobject
st otheusers.I
nsi mplerterms,i
tis distincti
onr esultsi ndiff
erentr equir
ement sofusage.I not herwor ds,
usedtoconf eraut hori
zati
on.It
sbasicsyntaxi
s: therei snodef i
nit
et emplatei nimplement ingasubquer y.
GRANT<pr i
v i
lege_name> Subquer iesar ef l
exibl
eandat ouchofper sonalprefer
encesmaycome
ON<obj ect_name> i
nt opl aywhenusi ngit.Therear ecertainsi t
uati
onswher einy oumayor
TO<userorr ole_name> may notuse a subquer y.Butt here ar e also situat i
ons wher e
where: subquer iesar etheabsol utef i
tforapar ti
culartaskathand.
 pr ivi
lege_namei stheaccessri
ghtorpri
vilegegrantedtothe Asubquer yi saquer ythati scontainedwi t
hinotherquer ies.Itcanbe
user .Someoft heaccessr i
ghtsareALL,EXECUTE,and
i
nser t
edi nt oanycl ausesint heSELECTst atement.Also,i
ti saSELECT
SELECT.
statementt hati sinsertedinanot herSELECTst atement .
SELECTcol umnl i
st
 object
_namei
sthenameofadat abaseobj
ectl
i
keTABLE,
FROM t abl elist
VIEW,STOREDPROCandSEQUENCE.
WHEREcondi ti
on
Inthesecl auses,asubquer ymaybei nser t
ed.Howev er,themanneri n
 user
_nameist henameoftheusertowhom anaccessr i
ght whi ch t he subquer y willbe st ated and used i s sl
ight l
y dif f
erent,
i
sbeinggranted.PUBLI
Cisusedtograntaccessri
ght
stoall
dependi ngonwhet herthesubquer yisusedi nacol umnlist,at ableli
st,
user
s.Thisusernamer ef
erstoal
lthecurrentandsoon-
to-
beusersofthesystem. oracondi tion.
Student No Student Name
 r ole_
nameorr ol esareasetofpr i
vil
egesgroupedtoget
her. 001 AnneSmi th
GRANTSELECTONSt udent Info 002 JohnNav arro
TOJuani t
o 003 Bil
lyCrawf ord
TheGRANTcommand( codesabov e)wi
llgiveJuanit
o( t
heuser)the
SELECTaut hor
izati
onont het bl
St udentI
nfotable. ORnum St
udent
No Amt
Pd Payment
Mo
GRANTUPDATE( Student No) de
ONSt udentI
nfo 1 001 16000.
00 Cash
TOJuani t
o,Juanit
a 2 002 3000.
00 I
nstal
l
ment
TheGRANTcommand( codesabov e)wil
lgi
v eJuani
toandJuanitathe 3 002 5000.
00 I
nstal
l
ment
updateauthori
zationont heSt udent Nocol
umnoft hetblSt
udentI
nfo 4 002 1500.
00 I
nstal
l
ment
tabl
e. 5 003 10500.
00 Cash

Torevokeanaut hor
izat
ionfrom auser,
theREVOKEcommandi sused. SELECTSt udentName,
I
ttakesaformt hatisalmostsi
mi l
artotheGRANTstatement: (SELECTSUM( AmtPd)
REVOKE<pr i
vil
ege_name> FROM t blFees
ON<object_name> WHERESt udentNo=tblSt
udents.St
udentNo
FROM <userorrole_name> ANDPay ment Mode=‘ I
nstal
lment’)
where: AS‘Total AmountPai dbyInstal
l
ment ’
 pr iv
il
ege_namei stheaccessr i
ghtorpr
ivi
l
egerevokedfrom FROM t blStudents
theuser Thest atementabov eshowsani mplementat
ionofasubquer
y.The
subquer yont heexampleistheoneenclosedinpar
ent
hesi
s,whi
chi
s:

Page15of15
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

SELECTSUM( Amt Pd)


FROM t blFees SELECTSt udent NameFROM t blSt udent s
WHERESt udent No=t blStudent s.Student No LEFTJOI Nt blFees
ANDPay ment Mode=‘ Inst allment ’ ONt bl Student s.St udent No=t blFees. StudentNo
Themai nst at ementont heexampl e, withoutt hesubquer y,i
s: GROUPBY
SELECTSt udent Name tblSt udent s.St udent No, Student Name
FROM t blSt udent s HAVI NGSUM( Amt Pd)<10000
Theexampl ewi llr esultt oav i
ew ofal lt hest udent sandt het otal The abov e st atementpr oduces t he same out putas t hatoft he
amountt hatt heyhav epai dt hroughi nstallment .SinceAnneSmi thand stat ementonSl ide9.Wi t
houtasubquer y,youhav etouset heGROUP
Bill
yCr awf or dpai dincash,t hev alueoft hei rtotalamountpai din
BY cl auset o av oi dr epet iti
on ofr owsand t heHAVI NG cl auset o
i
nst al l
mentwasl ef tnullsi ncenov aluecanbegi ven.
Thesubquer yi snecessar yt oobt aint hiski ndofdat abecauset hereis enf or cet hecondi ti
ont hatonl yt hoset hathav epai dat otalamountof
noequi valentsi ngl equer yf ort his. l
esst han10, 000. 00wi llbedi spl ay ed.
SELECTSt udent Name Ifyouwoul dl ikeal istofst udent s,al ongwi t
ht hecountoft henumber
FROM t blSt udent s ofpay mentt ransact ionst hatt heyhav edone,t hest atementbel owon
WHERESt udent NoI N thesl idewi l
l accompl ishit .
(SELECTSt udent NoFROM t bl Fees SELECTSt udent Name,
WHEREPay ment Mode=‘ Inst allment ’) (SELECTCOUNT( St udent No)
Forexampl e,y ouwantt or etrievet hest udent swhosepay mentmode FROM t blFees
i
si ncashbasi s.Itcanbeaccompl i
shedusi ngt hest atementabov e. WHERE
Int he out put ,John Nav ar ro was noti ncl uded si nce he isi nthe tblSt udent s.St udent No=t blFees. St udent No)
AS' NumberofPay mentTr ansact i
ons'
Instal l
ment basi s.Not i
ce t hat t he subquer y was pl aced wi thi
n FROM t blStudent s
par enthesesf ort heI Nkey wor d.Al so, theSt udent Nocol umnwasused ORDERBYt bl St udent s.St udent No
toconnectt het woquer i
es.Ev ent houghwewant edt heout putto Thest atementabov edemonst ratest hegener aluseofsubquer ies
displ ay t he St udent Name, we used St udentNo t o def i
ne t he whi chi sacal cul atedcol umn.I ti sal soacor r
elatedsubquer y.
relationshipbet weent het blSt udent sandt het blFeest able. SELECTSt udent Name,
Cant hest at ementont hesl idebedonewi thoutasubquer y? COUNT( Student No)
Theanswert ot hequest ioni sy es.Thequer iesshownont heslideare AS' NumberofPay mentTr ansact i
ons'
FROM t blStudent s
equi valentt oSt at ementAonSl ide5.Wi thoutt hesubquer y,youcan LEFTJOI Nt blFees
direct l
yconnectt het blSt udent sandt blFeest ablebuty ouhav et ouse ON
theGROUPBYcl auset oensur et hatonl yoner ow percust omeri s tblSt udent s.St udent No=t blFees. St udent No
displ ayed.I fy our emov et heGROUPBYcl auseonquer iesBandC, the GROUPBY
out putwi llbe: tblSt udent s.St udent No, Student Name
ORDERBYt bl St udent s.Student No
Student Name Thest atementabov eisanequi v alentofSt atementAonSl ide11.Bot h
JohnNav ar ro
stat ement swi llpr oducet hesameout put.Theonl ydi f
ferencei sthat
JohnNav ar ro
JohnNav ar ro Stat ementBhasnosubquer y.
CHAPTER11
Exampl e #2 oft he Usi ng Subquer ies topici s an exampl e ofan Af unct ionaldependencydescr ibest her el
ationshipbet weenat tri
butes
uncorrelat ed subquer y.Meani ng,i ti s unr elated and compl etel
y (columns)i nat abl e.Iti saconst raintbet weent woset sofat tri
butes
i
ndependentoft heout erquer y. formt hedat abase.
Ont heot herhand, correlatedsubquer iesar especi f
ical
lyrel
atedt othe
outerquer y.Becauseoft hisr elationship,cor r
elatedquer i
esneedt obe
evaluatedf oreachr owr etur nedandcanpr oducedi ffer
entresult
seach
ti
met hesubquer yisexecut ed.
Sti
llusingt heSt udentsandt heFeest ables,ify ouwantt opr oducea
l
istofst udent s who hav e pai dat otalamountt hatisl ess than
10,000.00r egar dlessofwhat evert hepay mentmode,t hest at
ement
canbe:
SELECTSt udent NameFROM t blStudent s
WHERE( SELECTSUM( Amt Pd)
FROM t blFees i
fAandBar eat tri
butesofat able,Bisf uncti
onal l
ydependentonA,if
WHERE eachvalueofAi sassociatedwithex actl
yonev alueofB.
tbl
Student s.Student No=t blFees. StudentNo) Anattri
buteoragr oupofat t
ri
butesont hel efthandsi deofthearr
ow
<10000 ofafuncti
onal dependencyisreferredtoas' determinant'
.
Thesubquer yi nthestat ementi s: Funct
ionaldependencycanbecl assifi
edast hef oll
owing:
SELECTSUM( Amt Pd)  Ful lFunct i
onaldependencyi ndicatest hatifA andB ar e
FROM t blFees att
ributes (columns)ofa t able,B i sf ull
yfuncti
onal
ly
WHEREt blSt udents.St
udent No=t blFees.StudentNo dependentonAi fBisf uncti
onallydependentonA,butnot
Iti
scor r
el atedbecausei tcannotbeexecut edoni tsown.I fexecuted onanypr opersubsetofA.
withoutt he out erormai n quer y,an er rorwi lloccurbecause t he
tbl
Student s.Student Nocol umndoesn’ texi stwithint hecontextoft he  Par
tialFunct
ionalDependencyindi
cat
esthatifAandBare
subquer y.Samewi t
hExampl e#1 at
tri
butesofat abl
e,Bisparti
all
ydependentonAift
her
eis

Page16of16
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

someat tr
ibut
et hatcanber
emov
edf
rom A andy
ett
he acolumnofat e;at
abl omi
cref
erst
osi
mpl
e,i
ndi
vi
si e;andat
bl upl
e
dependencysti
ll
holds. r
efer
stoarowi
natable.

 Transit
iveFunctionalDependencyi sacondi ti
onwhereA,B, 1NFdisal
l
owshavi
ngasetofval
ues,arowofv al
ues,
oracombi
nat
ion
andCar eattr
ibutesofat ablesucht hat,i
fAi sfunct
ionall
y ofbot
hasanatt
ri
butev
aluef
orasingl
et upl
e.
dependentonBandBi sf uncti
onallydependentonCt henC
sTr
i ansiti
vel
ydependentonAvi aB. Ar el
ati
onisi nthesecondnor malform( 2NF)ifandonlyifiti
sin1NF
Normal i
zati
on i st he pr ocess of or ganizi
ng dat a to minimize andev er
ynon- keyattr
ibuteisf ul
lydependentont hepri
mar ykey
.Itis
redundancyint hedesignofar elati
onal databasemanagementsy st
em accomplishedbyel i
minatingpar t
ialdependencies.
(RDBMS) .Itrefer
st oaser i
esofr ecommendedst epstakentoremov e Toputat ablein2NFr equiresthaty ouidenti
fythepri
mar ykey,and
redundancyandupdat eanomal i
esf rom adat abasedesign. thatyoudet erminether elat
ionshipbetweent hepart
soft hekeyand
Normal i
zati
oni st hespeci f
icpr ocesst hatal l
owsdesi gner
stot urn thedata.
unstruct
ureddat ai nto apr operlydesignedsetoft ablesanddat a
elements. Ar elati
oni si
nthi
rdnor malformifandonl yifiti
sin2NFandev er
ynon
-keyat tr
ibutei
snon-transit
ivel
y(ordi
rectly)dependentontheprimary
Thet womai ngoal
sofnormal
izat
ionarethefoll
owing:
oEl i
mi nat
eredundantdat
a.Thisisimportantbecausewhendatais key.I notherwords,eachcol umnisdirectlydependentontheprimary
repeated,anychangestopar
ti
cularv
aluesaf f
ectmulti
pler
owsrat
her keywhi l
enon- pr
imarykeycol umnsar en’tdependentonot hernon-
thanjustone. primar ykeycolumns.
Student No StudName Pr ogramCode,ProgramDesc
oEl i
minat
einsert
,delete,andupdat eanomal i
es.Thisgoalisal
so 0618 Dy, Lea BSI T, BS in Inf
ormati
on
rel
atedtothefi
rstgoal.Forinstance,i
fthereisar epeat
eddataofa Technol ogy
Student
’snamei nat ableandi fthatstudent’
snameneedst obe 0679 Sant os,
Er i
c BSCS, BSinComputerSci
ence
revi
sedbecauseoftypographicalerr
orsbyt heonewhoencodedi t
,a
l
argeamountofdataneedst obeupdat edratherthanj
ustone.
Theunnormali
zedtabl
e(Tabl
e11.1)i
sthet
blSt
udentt
abl
e.Not
icet
he
Anotherexampl eisfortheinsertanomal y.Forinstance,youdon’thave col
umnnamedPr ogramCode,Progr
amDesc.Thesaidcol
umni sa
tableforstudenti nformati
onandy ouonl yhav eat ableforstudents mult
ival
uedcolumnwhichisdi
sal
l
owedina1NF.
andt heirgrades.Ifanewst udentcomesandy ouwoul dwantt oadd
thatstudentsomewher einy ourdat abase,y ouwoul dbeabl et
odoso So,t o el
iminat
et he multi
val
ued col
umn and t otransf
orm t
he
sincethatnewst udentsti
lldoesn’thav egr adesy et
. tbl
Studentinto 1NF,we separat
et he v
alues.The Progr
amCode,
Lastly,
adel eteanomal ywoul doccuri fyouwant edtodelet
ear owbut
ProgramDesc column wil
lnow be two diff
erentcol
umns namel
y
doing so woul d el
iminate some r el
ated pi ece ofi nf
ormati
on.For
ProgramCodeandPr ogr
amDesc.
exampl e,youhav eat abl
econt aining st udentinformati
onwi thno
uniquei denti
fierorpr imarykeyandy ouwantt o del
eteast udent
whosel astnamei sPer ez.Del eti
ngaspeci f
icPer ezwilldel
eteall Usingt het blStudenti nt hef i
rstnor malf or m, wewi lltransf ormi ttot he
studentswi t
ht hesamel astname. secondnor malf orm byel iminat i
ngt hecol umnst hatar enotf ully
dependentont hepr i
mar ykey .So,t hesecondnor malf or m wi llresul t
Thethreemai nr ulesfornor mal i
zingdataar ethefollowing: tot he t blStudentwi thj ustt he pr imar y key ( St udent No)and t he
1. El i
mi naterepeat ingdat a.Thisr uleisal laboutdi sall
owing
Student Namecol umn.
mul t
ivaluedattributes.Forinstance,av aluel i
keBlue,Redi s
notal lowedt o exi stinaCal endar Colorcol umn.Mul ti
ple Tocompl etethenor mal i
zat i
onpr ocessunt i
lt het hi rdnor malf or m, the
val
uesi nasi nglecel lwi l
lobv i
ousl ycreatedi ff
icult
iesi n columns t hatar e notdi rectly dependenton t he t abl e mustbe
ret
rievingdatabyanyspeci f
iedv alue. eli
mi nat ed.Weendi thav ingt hreet ablesnamel yt het bl Studentwi th
Aresul ttot hisr ul
ei st hatr epeatedcol umnsar enotal l
owed.For theSt udent NoandSt udent Namecol umns;t hePr ogr am t abl ewi tht he
i
nstance,anal ternati
vetonothav ingmul tiplev al
uesi nasinglecol umn Progr amCodeandPr ogr amDesccol umns,andt heSt udent Progt able
wit
ht heexampl eabov ei screat i
ngCal endar Color1f ortheBl uev al
ue, witht heSt udent NoandPr ogramCodecol umns.
andcr eat
ingCal endarCol or2f ortheRedv alue.Butt hisal ter
native
Boy ce–Coddnor malf orm( BCNF)i sasl i
ght l
yst rongerv ersionoft he
wouldnotbeper mitt
ed.Repeat eddata, whet heritismul ti
plev al
uesi n
thi
rdnor malf or m.I thandl esapr oblem wi thanent ityt hatmi ghthav e
a single column ormul ti
ple columns t o handl e similardat a,i s
twopr i
mar ykey s.
di
sallowedandunwant ed.
Thisnor malf or m wasnamedaf terRayBoy cewhowasoneoft he
creator s ofSQL,and EdgarCodd who i st he f at herofr elational
2. Eli
minate part
ialdependenci
es.Thi
sr efersto sit
uati
ons
databases.BCNFencompassest hesecondandt hi rdnor malf orms.I t
wheretheprimarykeyforatabl
eisacomposi t
eprimarykey
,
i
ssl ight l
yst ri
ct ert hant het hirdnor mal f
or m.
whichmeans‘ akeycomposedofmul tiplecolumns’
.This
BCNFel imi natesmostoft heanomal i
esknowni ndat abasest oday ,
rul
estatesthatnocolumni nt
hetabl
ecanber elat
edonlyto
apartoftheprimarykey. andi ti st hemostcommonst andar df ornor mal izat ioni ncommer cial
databasesandcomput er-aidedsof twar eengi neer ingt ool s.
3. El iminat
et r
ansitivedependenci es.Thi srefer
st osituations Ar elat i
oni si nt hef our thnor malf or m( 4NF)i fandonl yi faMul ti-
whereinacol umni nt hetabl
er eferst oanon- keycol umn ValuedDependency( MVD)exi stsi nat ablet henal lat tributesoft he
i
nsteadofreferri
ngt ot heprimarykeyofat able. tablear eal sof unct i
onal l
ydependentonA.
TheFi rstNor malForm( 1NF)st atesthatthedomai nofanat t
ribute Thef i
fthnor malf orm( 5NF)i sal socal l
edt hepr oj ect ion- j
oinnor mal
musti ncludeonlyatomi cv al
uesandt hatt
hev alueofanyat tr
ibuteina form( PJ/ NF) .
tuplemustbeasi nglevaluef rom t hedomai noft hatatt
r i e.Domai
but n Ar elationi sint hef i
ft
hnor mal formi fandonl yi fev er yj oindependency
referstot hesetofpossi blev aluesforagi venat t
ri
bute,andcanbe i
nt her el ati
oni saconsequenceoft hecandi dat ekey soft her elati
on.
consideredaconst rai
ntont hev alueoftheat t
ribute;Att
ribut
er ef
er sto Not e:Acandi dat ekeyi sakeyt hatuni quel yident ifiesr owsi nat able.I t
Page17of17
Uni
ver
sit
yofCal
oocanCi
ty–Dat
abaseSy
stems 1stSemest
erSY:
2015
-
2016

canbeacombi nationofattr
ibutesthatcanbeuni quelyusedt oident
ify
adat abaserecordwi thoutanyextraneousdat a.Eacht abl
emayhav e
oneormor ecandidatekeys.
Though nor mali
zat i
on isthe prevail
ing pr i
ncipl
et hati s used and
fol
lowedwhendesi gni
ngadat abase,t herearest il
lotheralter
nativ
es
usedi ncert
ainsit
uat i
ons.
Forinstance,wheni tcomest odatawar ehousesy st
emsandsof t
ware,
severalpract
iti
onerspr ef
erusingast arschemadesi gnfordatabases
rat
hert hannormalizati
on.

Ast arschemadef inesdat aent itiesi nawayt hatsuppor tst hev iewof
thedeci sionmakeri nabusi ness,aswel last hedat aent it
iest hat
refl
ectt hei mpor tantoper ationalaspect sofabusi ness.I tisadat a
model i
ngt echni queusedt omapmul tidimensi onaldeci sionsuppor t
datai ntoar elational dat abase.
A cer tain amountofr edundancyi s al l
owed i n a st arschema.I t
emphasi zes t he cr eat ion ofa dat a st ructuret hatmor er ef lects
businessr eal it
ies,andal soonet hatal lowsf orqui ckpr ocessi ngof
databyspeci alanal ytical softwar e.
Themai ni deaofast arschemadesi gni st hatacent ralf actt ablei s
created, whi chi sr elatedt oanynumberofdi mensi ont ables.
Indat awar ehousi ng,af actt ableconsi stsofmeasur ement s,met ri
cs,
orf actsofabusi ness.Di mensi ont ablesusual lyhav ef ew recor ds
compar ed t of actt abl es,butmay hav eav eryl arge numberof
attr
ibutest hatdescr ibet hef actdat a.
Ont hesl idei sanexampl eofadat abasewi thast arschemadesi gn.I n
thedesi gn,t hecent ralf actt ablei st het blEnroll
mentt abl e.Thef i
rst
fourcol umns( St udent I
D,Pr ogr amCode,Sect i
onCode,andBi l
li
ngI D)i n
thef actt abl ear et her eonl ybecausei twi llrelat
et het abl et oeachof
the di mensi ons.Each di mensi on t able has a pr imar ykeyr elating
columnt ot hef actt able.Thenon- primar ykey soft hef actt ablemay
representameasur eormet rict hatcanbeusedi ncal culati
onsor
analysisofabusi nesst hatut il
izest hedat abasewhi l
et henon- pr imar y
keysoft hedi mensi ont ablesr epr esentaddi ti
onalat tributesoft he
dimensi ons

Page18of18

You might also like