Chapter 3: SQL

You might also like

You are on page 1of 66

Chapter3:SQL

DatabaseSystemConcepts,5thEd.
Silberschatz,KorthandSudarshan Seewww.dbbook.comforconditionsonreuse

Chapter3:SQL
s DataDefinition s BasicQueryStructure s SetOperations s AggregateFunctions s NullValues s NestedSubqueries s ComplexQueries s Views s ModificationoftheDatabase s JoinedRelations**

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

History
s IBMSequellanguagedevelopedaspartofSystemRprojectatthe

IBMSanJoseResearchLaboratory

s RenamedStructuredQueryLanguage(SQL) s ANSIandISOstandardSQL:
q q q q q

SQL86 SQL89 SQL92 SQL:1999(languagenamebecameY2Kcompliant!) SQL:2003

s Commercialsystemsoffermost,ifnotall,SQL92features,plus

varyingfeaturesetsfromlaterstandardsandspecialproprietary features.
q

Notallexamplesheremayworkonyourparticularsystem.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

DataDefinitionLanguage
Allowsthespecificationofnotonlyasetofrelationsbutalso informationabouteachrelation,including:
s Theschemaforeachrelation. s Thedomainofvaluesassociatedwitheachattribute. s Integrityconstraints s Thesetofindicestobemaintainedforeachrelations. s Securityandauthorizationinformationforeachrelation. s Thephysicalstoragestructureofeachrelationondisk.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

DomainTypesinSQL
s char(n).Fixedlengthcharacterstring,withuserspecifiedlengthn. s varchar(n).Variablelengthcharacterstrings,withuserspecifiedmaximum

lengthn.

s int.Integer(afinitesubsetoftheintegersthatismachinedependent). s smallint.Smallinteger(amachinedependentsubsetoftheinteger

domaintype).

s numeric(p,d).Fixedpointnumber,withuserspecifiedprecisionofpdigits,

withndigitstotherightofdecimalpoint.

s real,doubleprecision.Floatingpointanddoubleprecisionfloatingpoint

numbers,withmachinedependentprecision. digits.

s float(n).Floatingpointnumber,withuserspecifiedprecisionofatleastn s MorearecoveredinChapter4.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

CreateTableConstruct
s AnSQLrelationisdefinedusingthecreatetablecommand:

createtabler(A1D1,A2D2,...,AnDn, (integrityconstraint1), ..., (integrityconstraintk)) risthenameoftherelation q eachAiisanattributenameintheschemaofrelationr


q q

DiisthedatatypeofvaluesinthedomainofattributeAi

s Example:

createtablebranch (branch_name char(15)notnull, branch_city char(30), assets integer)

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

IntegrityConstraintsinCreateTable
s notnull s primarykey(A1,...,An)

Example:Declarebranch_nameastheprimarykeyforbranch . createtablebranch (branch_name char(15), branch_city char(30), assets integer, primarykey(branch_name))

primarykeydeclarationonanattributeautomaticallyensures notnullinSQL92onwards,needstobeexplicitlystatedin SQL89


DatabaseSystemConcepts,5thEd.,June2006 3.<number> Silberschatz,KorthandSudarshan

DropandAlterTableConstructs
s Thedroptablecommanddeletesallinformationaboutthedropped

relationfromthedatabase. relation:

s Thealtertablecommandisusedtoaddattributestoanexisting

altertableraddAD

whereAisthenameoftheattributetobeaddedtorelationrandD isthedomainofA.
q

Alltuplesintherelationareassignednullasthevalueforthe newattribute.

s Thealtertablecommandcanalsobeusedtodropattributesofa

relation:

altertablerdropA whereAisthenameofanattributeofrelationr
q

Droppingofattributesnotsupportedbymanydatabases

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

BasicQueryStructure
s SQLisbasedonsetandrelationaloperationswithcertain

modificationsandenhancements

s AtypicalSQLqueryhastheform:

selectA1,A2,...,An fromr1,r2,...,rm whereP


q Airepresentsanattribute q Rirepresentsarelation q Pisapredicate. s Thisqueryisequivalenttotherelationalalgebraexpression.

A ,A ,,A ( P (r1 r2 rm ))
1 2 n

s TheresultofanSQLqueryisarelation.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

TheselectClause
s Theselectclauselisttheattributesdesiredintheresultofaquery
q

correspondstotheprojectionoperationoftherelationalalgebra selectbranch_name fromloan branch_name(loan)

s Example:findthenamesofallbranchesintheloanrelation:

s Intherelationalalgebra,thequerywouldbe: s NOTE:SQLnamesarecaseinsensitive(i.e.,youmayuseupperor

lowercaseletters.)
q q

E.g.Branch_Name

BRANCH_NAME

branch_name

Somepeopleuseuppercasewhereverweuseboldfont.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

TheselectClause(Cont.)
s SQLallowsduplicatesinrelationsaswellasinqueryresults. s Toforcetheeliminationofduplicates,insertthekeyworddistinctafter

select.

s Findthenamesofallbranchesintheloanrelations,andremove

duplicates

selectdistinctbranch_name fromloan
s Thekeywordallspecifiesthatduplicatesnotberemoved.

selectallbranch_name fromloan

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

TheselectClause(Cont.)
s Anasteriskintheselectclausedenotesallattributes

select* fromloan
s Theselectclausecancontainarithmeticexpressionsinvolvingthe

operation,+,,,and/,andoperatingonconstantsorattributesof tuples. selectloan_number,branch_name,amount100 fromloan wouldreturnarelationthatisthesameastheloanrelation,exceptthat thevalueoftheattributeamountismultipliedby100.

s Thequery:

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ThewhereClause
s Thewhereclausespecifiesconditionsthattheresultmustsatisfy
q

Correspondstotheselectionpredicateoftherelationalalgebra.

s TofindallloannumberforloansmadeatthePerryridgebranchwith

loanamountsgreaterthan$1200.

selectloan_number fromloan wherebranch_name='Perryridge'andamount>1200


s Comparisonresultscanbecombinedusingthelogicalconnectivesand,

or,andnot.

s Comparisonscanbeappliedtoresultsofarithmeticexpressions.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ThewhereClause(Cont.)
s SQLincludesabetweencomparisonoperator s Example:Findtheloannumberofthoseloanswithloanamountsbetween

$90,000and$100,000(thatis, $90,000and $100,000) selectloan_number fromloan whereamountbetween90000and100000

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ThefromClause
s Thefromclauseliststherelationsinvolvedinthequery
q

CorrespondstotheCartesianproductoperationoftherelationalalgebra.

s FindtheCartesianproductborrowerXloan

select fromborrower,loan sFindthename,loannumberandloanamountofallcustomers havingaloanatthePerryridgebranch. selectcustomer_name,borrower.loan_number,amount fromborrower,loan whereborrower.loan_number=loan.loan_numberand branch_name='Perryridge'

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

TheRenameOperation
s TheSQLallowsrenamingrelationsandattributesusingtheasclause:

oldnameasnewname
s Findthename,loannumberandloanamountofallcustomers;renamethe

columnnameloan_numberasloan_id.

selectcustomer_name,borrower.loan_numberasloan_id,amount fromborrower,loan whereborrower.loan_number=loan.loan_number

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

TupleVariables
s Tuplevariablesaredefinedinthefromclauseviatheuseoftheas

clause.

s Findthecustomernamesandtheirloannumbersforallcustomers

havingaloanatsomebranch.

selectcustomer_name,T.loan_number,S.amount fromborrowerasT,loanasS whereT.loan_number=S.loan_number


sFindthenamesofallbranchesthathavegreaterassetsthan

somebranchlocatedinBrooklyn.

selectdistinctT.branch_name frombranchasT,branchasS whereT.assets>S.assetsandS.branch_city='Brooklyn'

sKeywordasisoptionalandmaybeomitted borrowerasT borrowerT

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

StringOperations
s SQLincludesastringmatchingoperatorforcomparisonsoncharacter

strings.Theoperatorlikeusespatternsthataredescribedusingtwo specialcharacters:
q q

percent(%).The%charactermatchesanysubstring. underscore(_).The_charactermatchesanycharacter.

s Findthenamesofallcustomerswhosestreetincludesthesubstring

Main.

selectcustomer_name fromcustomer wherecustomer_streetlike'%Main%'

s MatchthenameMain%
like'Main\%' escape'\'

s SQLsupportsavarietyofstringoperationssuchas
q q q

concatenation(using||) convertingfromuppertolowercase(andviceversa) findingstringlength,extractingsubstrings,etc.


3.<number> Silberschatz,KorthandSudarshan

DatabaseSystemConcepts,5thEd.,June2006

OrderingtheDisplayofTuples
s Listinalphabeticorderthenamesofallcustomershavingaloanin

Perryridgebranch

selectdistinctcustomer_name fromborrower,loan whereborrowerloan_number=loan.loan_numberand branch_name='Perryridge' orderbycustomer_name


s Wemayspecifydescfordescendingorderorascforascending

order,foreachattribute;ascendingorderisthedefault.
q

Example:orderbycustomer_namedesc

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

Duplicates
s Inrelationswithduplicates,SQLcandefinehowmanycopiesoftuples

appearintheresult.

s Multisetversionsofsomeoftherelationalalgebraoperatorsgiven

multisetrelationsr1andr2:

1. (r1):Iftherearec1copiesoftuplet1inr1,andt1satisfies selections,,thentherearec1copiesoft1in(r1). 2. A(r):Foreachcopyoftuplet1inr1,thereisacopyoftupleA (t1)inA(r1)whereA(t1)denotestheprojectionofthesingletuple t1.

3. r1xr2:Iftherearec1copiesoftuplet1inr1andc2copiesoftuple t2inr2,therearec1xc2copiesofthetuplet1.t2inr1xr2

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

Duplicates(Cont.)
s Example:Supposemultisetrelationsr1(A,B)andr2(C)areas

follows:

r1={(1,a)(2,a)}r2={(2),(3),(3)}
s ThenB(r1)wouldbe{(a),(a)},whileB(r1)xr2wouldbe

{(a,2),(a,2),(a,3),(a,3),(a,3),(a,3)}
s SQLduplicatesemantics:

selectA1,,A2,...,An fromr1,r2,...,rm whereP

isequivalenttothemultisetversionoftheexpression:

A1,A2 ,,An ( P (r1 r2 rm ))

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

SetOperations
s Thesetoperationsunion,intersect,andexceptoperateonrelations

andcorrespondtotherelationalalgebraoperations, , .

s Eachoftheaboveoperationsautomaticallyeliminatesduplicates;to

retainallduplicatesusethecorrespondingmultisetversionsunionall, intersectallandexceptall. Supposeatupleoccursmtimesinrandntimesins,then,itoccurs:


q q q

m+ntimesinrunionalls min(m,n)timesinrintersectalls max(0,mn)timesinrexceptalls

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

SetOperations
s Findallcustomerswhohavealoan,anaccount,orboth:

(selectcustomer_namefromdepositor) union (selectcustomer_namefromborrower)


sFindallcustomerswhohavebothaloanandanaccount.

(selectcustomer_namefromdepositor) intersect (selectcustomer_namefromborrower)


sFindallcustomerswhohaveanaccountbutnoloan.

(selectcustomer_namefromdepositor) except (selectcustomer_namefromborrower)

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

AggregateFunctions
s Thesefunctionsoperateonthemultisetofvaluesofacolumnof

arelation,andreturnavalue

avg:averagevalue min:minimumvalue max:maximumvalue sum:sumofvalues count:numberofvalues

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

AggregateFunctions(Cont.)
s FindtheaverageaccountbalanceatthePerryridgebranch.

selectavg(balance) fromaccount wherebranch_name='Perryridge'


sFindthenumberoftuplesinthecustomerrelation.

selectcount(*) fromcustomer
sFindthenumberofdepositorsinthebank.

selectcount(distinctcustomer_name) fromdepositor

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

AggregateFunctionsGroupBy
s Findthenumberofdepositorsforeachbranch.

selectbranch_name,count(distinctcustomer_name) fromdepositor,account wheredepositor.account_number=account.account_number groupbybranch_name

Note:Attributesinselectclauseoutsideofaggregatefunctionsmust appearingroupbylist

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

AggregateFunctionsHavingClause
s Findthenamesofallbrancheswheretheaverageaccountbalanceis

morethan$1,200.

selectbranch_name,avg(balance) fromaccount groupbybranch_name havingavg(balance)>1200 Note:predicatesinthehavingclauseareappliedafterthe formationofgroupswhereaspredicatesinthewhere clauseareappliedbeforeforminggroups

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

NullValues
s Itispossiblefortuplestohaveanullvalue,denotedbynull,forsome

oftheirattributes

s nullsignifiesanunknownvalueorthatavaluedoesnotexist. s Thepredicateisnullcanbeusedtocheckfornullvalues.
q

Example:Findallloannumberwhichappearintheloanrelation withnullvaluesforamount. selectloan_number fromloan whereamountisnull

s Theresultofanyarithmeticexpressioninvolvingnullisnull
q

Example:5+nullreturnsnull Moreonnextslide

s However,aggregatefunctionssimplyignorenulls
q

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

NullValuesandThreeValuedLogic
s Anycomparisonwithnullreturnsunknown
q

Example:5<nullornull<>nullornull=null OR:(unknownortrue)=true, (unknownorfalse)=unknown (unknownorunknown)=unknown AND:(trueandunknown)=unknown, (falseandunknown)=false, (unknownandunknown)=unknown NOT:(notunknown)=unknown PisunknownevaluatestotrueifpredicatePevaluatesto unknown

s Threevaluedlogicusingthetruthvalueunknown:
q

q q

s Resultofwhereclausepredicateistreatedasfalseifitevaluatesto

unknown

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

NullValuesandAggregates
s Totalallloanamounts

selectsum(amount) fromloan
q q

Abovestatementignoresnullamounts Resultisnullifthereisnononnullamount

s Allaggregateoperationsexceptcount(*)ignoretupleswithnull

valuesontheaggregatedattributes.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

NestedSubqueries
s SQLprovidesamechanismforthenestingofsubqueries. s Asubqueryisaselectfromwhereexpressionthatisnestedwithin

anotherquery.

s Acommonuseofsubqueriesistoperformtestsforsetmembership,set

comparisons,andsetcardinality.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ExampleQuery
s Findallcustomerswhohavebothanaccountandaloanatthebank.

selectdistinctcustomer_name fromborrower wherecustomer_namein(selectcustomer_name fromdepositor)


sFindallcustomerswhohavealoanatthebankbutdonothave

anaccountatthebank

selectdistinctcustomer_name fromborrower wherecustomer_namenotin(selectcustomer_name fromdepositor)

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ExampleQuery
s Findallcustomerswhohavebothanaccountandaloanatthe

Perryridgebranch

selectdistinctcustomer_name fromborrower,loan whereborrower.loan_number=loan.loan_numberand branch_name='Perryridge'and (branch_name,customer_name)in (selectbranch_name,customer_name fromdepositor,account wheredepositor.account_number= account.account_number)


sNote:Abovequerycanbewritteninamuchsimplermanner.The

formulationaboveissimplytoillustrateSQLfeatures.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

SetComparison
s Findallbranchesthathavegreaterassetsthansomebranchlocated

inBrooklyn.

selectdistinctT.branch_name frombranchasT,branchasS whereT.assets>S.assetsand S.branch_city='Brooklyn'


sSamequeryusing>someclause

selectbranch_name frombranch whereassets>some (selectassets frombranch wherebranch_city='Brooklyn')

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

DefinitionofSomeClause
s F<comp>somer t r suchthat(F<comp>t)

Where<comp>canbe:<, , >, =,

(5<some

0 5 6 0 5 0 5 0 5

)=true

(read:5<sometupleintherelation)

(5<some (5=some (5some

)=false )=true )=true(since05)

(=some)in However,(some)notin
DatabaseSystemConcepts,5thEd.,June2006 3.<number> Silberschatz,KorthandSudarshan

ExampleQuery
s Findthenamesofallbranchesthathavegreaterassetsthanall

brancheslocatedinBrooklyn.

selectbranch_name frombranch whereassets>all (selectassets frombranch wherebranch_city='Brooklyn')

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

DefinitionofallClause
s F<comp>allr t r (F<comp>t)

(5<all

0 5 6 6 10 4 5 4 6

)=false

(5<all (5=all (5all

)=true )=false )=true(since54and56)

(all)notin However,(=all)in

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

TestforEmptyRelations
s Theexistsconstructreturnsthevaluetrueiftheargumentsubqueryis

nonempty.

s existsr r s notexistsr r=

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ExampleQuery
s Findallcustomerswhohaveanaccountatallbrancheslocatedin

Brooklyn.

selectdistinctS.customer_name fromdepositorasS wherenotexists( (selectbranch_name frombranch wherebranch_city='Brooklyn') except (selectR.branch_name fromdepositorasT,accountasR whereT.account_number=R.account_numberand S.customer_name=T.customer_name))
sNotethatXY=X Y sNote:Cannotwritethisqueryusing=allanditsvariants

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

TestforAbsenceofDuplicateTuples
s Theuniqueconstructtestswhetherasubqueryhasanyduplicate

tuplesinitsresult. branch.

s FindallcustomerswhohaveatmostoneaccountatthePerryridge

selectT.customer_name fromdepositorasT whereunique( selectR.customer_name fromaccount,depositorasR whereT.customer_name=R.customer_nameand R.account_number=account.account_numberand account.branch_name='Perryridge')

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ExampleQuery
s FindallcustomerswhohaveatleasttwoaccountsatthePerryridge

branch.

selectdistinctT.customer_name fromdepositorasT wherenotunique( selectR.customer_name fromaccount,depositorasR whereT.customer_name=R.customer_nameand R.account_number=account.account_numberand account.branch_name='Perryridge')


s Variablefromouterlevelisknownasacorrelationvariable

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

DerivedRelations
s SQLallowsasubqueryexpressiontobeusedinthefromclause s Findtheaverageaccountbalanceofthosebrancheswheretheaverage

accountbalanceisgreaterthan$1200.

selectbranch_name,avg_balance from(selectbranch_name,avg(balance) fromaccount groupbybranch_name) asbranch_avg(branch_name,avg_balance) whereavg_balance>1200 Notethatwedonotneedtousethehavingclause,sincewecompute thetemporary(view)relationbranch_avginthefromclause,andthe attributesofbranch_avgcanbeuseddirectlyinthewhereclause.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

WithClause
s Thewithclauseprovidesawayofdefiningatemporaryviewwhose

definitionisavailableonlytothequeryinwhichthewithclause occurs.

s Findallaccountswiththemaximumbalance

withmax_balance(value)as selectmax(balance) fromaccount selectaccount_number fromaccount,max_balance whereaccount.balance=max_balance.value

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ComplexQueriesusingWithClause
s Findallbrancheswherethetotalaccountdepositisgreaterthanthe

averageofthetotalaccountdepositsatallbranches.

withbranch_total(branch_name,value)as selectbranch_name,sum(balance) fromaccount groupbybranch_name withbranch_total_avg(value)as selectavg(value) frombranch_total selectbranch_name frombranch_total,branch_total_avg wherebranch_total.value>=branch_total_avg.value

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

Views
s Insomecases,itisnotdesirableforalluserstoseetheentirelogical

model(thatis,alltheactualrelationsstoredinthedatabase.)

s Considerapersonwhoneedstoknowacustomersname,loannumber

andbranchname,buthasnoneedtoseetheloanamount.Thisperson shouldseearelationdescribed,inSQL,by

(selectcustomer_name,borrower.loan_number,branch_name fromborrower,loan whereborrower.loan_number=loan.loan_number)


s Aviewprovidesamechanismtohidecertaindatafromtheviewof

certainusers.

s Anyrelationthatisnotoftheconceptualmodelbutismadevisibletoa

userasavirtualrelationiscalledaview.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ViewDefinition
s Aviewisdefinedusingthecreateviewstatementwhichhasthe

form

createviewvas<queryexpression> where<queryexpression>isanylegalSQLexpression.Theview nameisrepresentedbyv.


s Onceaviewisdefined,theviewnamecanbeusedtorefertothe

virtualrelationthattheviewgenerates.

s Whenaviewiscreated,thequeryexpressionisstoredinthe

database;theexpressionissubstitutedintoqueriesusingtheview.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ExampleQueries
s Aviewconsistingofbranchesandtheircustomers

createviewall_customeras (selectbranch_name,customer_name fromdepositor,account wheredepositor.account_number= account.account_number) union (selectbranch_name,customer_name fromborrower,loan whereborrower.loan_number=loan.loan_number)


sFindallcustomersofthePerryridgebranch

selectcustomer_name fromall_customer wherebranch_name='Perryridge'

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ViewsDefinedUsingOtherViews
s Oneviewmaybeusedintheexpressiondefininganotherview s Aviewrelationv1issaidtodependdirectlyonaviewrelationv2ifv2is

usedintheexpressiondefiningv1

s Aviewrelationv1issaidtodependonviewrelationv2ifeitherv1

dependsdirectlytov2orthereisapathofdependenciesfromv1to

v2

s Aviewrelationvissaidtoberecursiveifitdependsonitself.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ViewExpansion
s Awaytodefinethemeaningofviewsdefinedintermsofotherviews. s Letviewv1bedefinedbyanexpressione1thatmayitselfcontainuses

ofviewrelations. step:

s Viewexpansionofanexpressionrepeatsthefollowingreplacement

repeat Findanyviewrelationviine1 Replacetheviewrelationvibytheexpressiondefiningvi untilnomoreviewrelationsarepresentine1


s Aslongastheviewdefinitionsarenotrecursive,thisloopwill

terminate

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ModificationoftheDatabaseDeletion
s DeleteallaccounttuplesatthePerryridgebranch

deletefromaccount wherebranch_name='Perryridge'
s DeleteallaccountsateverybranchlocatedinthecityNeedham.

deletefromaccount wherebranch_namein(selectbranch_name frombranch wherebranch_city='Needham')

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ExampleQuery
s Deletetherecordofallaccountswithbalancesbelowtheaverageat

thebank.

deletefromaccount wherebalance<(selectavg(balance) fromaccount)


q

Problem:aswedeletetuplesfromdeposit,theaveragebalance changes SolutionusedinSQL:

1.First,computeavgbalanceandfindalltuplestodelete 2.Next,deletealltuplesfoundabove(withoutrecomputingavgor retestingthetuples)

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ModificationoftheDatabaseInsertion
s Addanewtupletoaccount

insertintoaccount values('A9732','Perryridge',1200) orequivalently insertintoaccount(branch_name,balance,account_number) values('Perryridge',1200,'A9732')


s Addanewtupletoaccountwithbalancesettonull

insertintoaccount values('A777','Perryridge',null)

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ModificationoftheDatabaseInsertion
s ProvideasagiftforallloancustomersofthePerryridgebranch,a$200

savingsaccount.Lettheloannumberserveastheaccountnumberforthe newsavingsaccount insertintoaccount selectloan_number,branch_name,200 fromloan wherebranch_name='Perryridge' insertintodepositor selectcustomer_name,loan_number fromloan,borrower wherebranch_name='Perryridge' andloan.account_number=borrower.account_number

s Theselectfromwherestatementisevaluatedfullybeforeanyofits

resultsareinsertedintotherelation(otherwisequerieslike insertintotable1select*fromtable1 wouldcauseproblems)

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

ModificationoftheDatabaseUpdates
s Increaseallaccountswithbalancesover$10,000by6%,allother

accountsreceive5%.
q

Writetwoupdatestatements: updateaccount setbalance=balance1.06 wherebalance>10000 updateaccount setbalance=balance1.05 wherebalance10000

q q

Theorderisimportant Canbedonebetterusingthecasestatement(nextslide)

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

CaseStatementforConditionalUpdates
s Samequeryasbefore:Increaseallaccountswithbalancesover

$10,000by6%,allotheraccountsreceive5%.

updateaccount setbalance=case whenbalance<=10000thenbalance*1.05 elsebalance*1.06 end

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

UpdateofaView
s Createaviewofallloandataintheloanrelation,hidingtheamount

attribute

createviewloan_branchas selectloan_number,branch_name fromloan


s Addanewtupletobranch_loan

insertintobranch_loan values('L37,'Perryridge) Thisinsertionmustberepresentedbytheinsertionofthetuple ('L37','Perryridge',null) intotheloanrelation

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

UpdatesThroughViews(Cont.)
s Someupdatesthroughviewsareimpossibletotranslateinto

updatesonthedatabaserelations
q

createviewvas selectloan_number,branch_name,amount fromloan wherebranch_name=Perryridge

insertintovvalues('L99','Downtown','23')
s Otherscannotbetranslateduniquely
q

insertintoall_customervalues('Perryridge','John')

Havetochooseloanoraccount,and createanewloan/accountnumber!

s MostSQLimplementationsallowupdatesonlyonsimpleviews

(withoutaggregates)definedonasinglerelation

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

JoinedRelations**
s Joinoperationstaketworelationsandreturnasaresultanother

relation.

s Theseadditionaloperationsaretypicallyusedassubquery

expressionsinthefromclause

s Joinconditiondefineswhichtuplesinthetworelationsmatch,and

whatattributesarepresentintheresultofthejoin.

s Jointypedefineshowtuplesineachrelationthatdonotmatchany

tupleintheotherrelation(basedonthejoincondition)aretreated.

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

JoinedRelationsDatasetsforExamples
s Relationloan

s Relationborrower

s Note:borrowerinformationmissingforL260andloan informationmissingforL155

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

JoinedRelationsExamples
s loaninnerjoinborroweron

loan.loan_number=borrower.loan_number

s loanleftouterjoinborroweron loan.loan_number=borrower.loan_number

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

JoinedRelationsExamples
s loannaturalinnerjoinborrower

s loannaturalrightouterjoinborrower

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

JoinedRelationsExamples
s loanfullouterjoinborrowerusing(loan_number)

s Findallcustomerswhohaveeitheranaccountoraloan(butnotboth) atthebank. selectcustomer_name from(depositornaturalfullouterjoinborrower) whereaccount_numberisnullorloan_numberisnull

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

EndofChapter3

DatabaseSystemConcepts,5thEd.
Silberschatz,KorthandSudarshan Seewww.dbbook.comforconditionsonreuse

Figure3.1:DatabaseSchema
branch(branch_name,branch_city,assets) customer(customer_name,customer_street,customer_city) loan(loan_number,branch_name,amount) borrower(customer_name,loan_number) account(account_number,branch_name,balance) depositor(customer_name,account_number)

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

Figure3.3:Tuplesinsertedintoloanand borrower

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

Figure3.4: Theloanandborrowerrelations

DatabaseSystemConcepts,5thEd.,June2006

3.<number>

Silberschatz,KorthandSudarshan

You might also like