Professional Documents
Culture Documents
Chapter 3: SQL
Chapter 3: SQL
Chapter 3: 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
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:
DiisthedatatypeofvaluesinthedomainofattributeAi
s Example:
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
IntegrityConstraintsinCreateTable
s notnull s primarykey(A1,...,An)
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:
A ,A ,,A ( P (r1 r2 rm ))
1 2 n
s TheresultofanSQLqueryisarelation.
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
TheselectClause
s Theselectclauselisttheattributesdesiredintheresultofaquery
q
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
s Thequery:
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
ThewhereClause
s Thewhereclausespecifiesconditionsthattheresultmustsatisfy
q
Correspondstotheselectionpredicateoftherelationalalgebra.
s TofindallloannumberforloansmadeatthePerryridgebranchwith
loanamountsgreaterthan$1200.
or,andnot.
s Comparisonscanbeappliedtoresultsofarithmeticexpressions.
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
ThewhereClause(Cont.)
s SQLincludesabetweencomparisonoperator s Example:Findtheloannumberofthoseloanswithloanamountsbetween
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
ThefromClause
s Thefromclauseliststherelationsinvolvedinthequery
q
CorrespondstotheCartesianproductoperationoftherelationalalgebra.
s FindtheCartesianproductborrowerXloan
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
TheRenameOperation
s TheSQLallowsrenamingrelationsandattributesusingtheasclause:
oldnameasnewname
s Findthename,loannumberandloanamountofallcustomers;renamethe
columnnameloan_numberasloan_id.
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
TupleVariables
s Tuplevariablesaredefinedinthefromclauseviatheuseoftheas
clause.
s Findthecustomernamesandtheirloannumbersforallcustomers
havingaloanatsomebranch.
somebranchlocatedinBrooklyn.
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
StringOperations
s SQLincludesastringmatchingoperatorforcomparisonsoncharacter
strings.Theoperatorlikeusespatternsthataredescribedusingtwo specialcharacters:
q q
percent(%).The%charactermatchesanysubstring. underscore(_).The_charactermatchesanycharacter.
s Findthenamesofallcustomerswhosestreetincludesthesubstring
Main.
s MatchthenameMain%
like'Main\%' escape'\'
s SQLsupportsavarietyofstringoperationssuchas
q q q
DatabaseSystemConcepts,5thEd.,June2006
OrderingtheDisplayofTuples
s Listinalphabeticorderthenamesofallcustomershavingaloanin
Perryridgebranch
order,foreachattribute;ascendingorderisthedefault.
q
Example:orderbycustomer_namedesc
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
Duplicates
s Inrelationswithduplicates,SQLcandefinehowmanycopiesoftuples
appearintheresult.
s Multisetversionsofsomeoftherelationalalgebraoperatorsgiven
multisetrelationsr1andr2:
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:
isequivalenttothemultisetversionoftheexpression:
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
SetOperations
s Thesetoperationsunion,intersect,andexceptoperateonrelations
andcorrespondtotherelationalalgebraoperations, , .
s Eachoftheaboveoperationsautomaticallyeliminatesduplicates;to
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
SetOperations
s Findallcustomerswhohavealoan,anaccount,orboth:
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
AggregateFunctions
s Thesefunctionsoperateonthemultisetofvaluesofacolumnof
arelation,andreturnavalue
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
AggregateFunctions(Cont.)
s FindtheaverageaccountbalanceatthePerryridgebranch.
selectcount(*) fromcustomer
sFindthenumberofdepositorsinthebank.
selectcount(distinctcustomer_name) fromdepositor
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
AggregateFunctionsGroupBy
s Findthenumberofdepositorsforeachbranch.
Note:Attributesinselectclauseoutsideofaggregatefunctionsmust appearingroupbylist
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
AggregateFunctionsHavingClause
s Findthenamesofallbrancheswheretheaverageaccountbalanceis
morethan$1,200.
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
NullValues
s Itispossiblefortuplestohaveanullvalue,denotedbynull,forsome
oftheirattributes
s nullsignifiesanunknownvalueorthatavaluedoesnotexist. s Thepredicateisnullcanbeusedtocheckfornullvalues.
q
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.
anaccountatthebank
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
ExampleQuery
s Findallcustomerswhohavebothanaccountandaloanatthe
Perryridgebranch
formulationaboveissimplytoillustrateSQLfeatures.
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
SetComparison
s Findallbranchesthathavegreaterassetsthansomebranchlocated
inBrooklyn.
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)
(=some)in However,(some)notin
DatabaseSystemConcepts,5thEd.,June2006 3.<number> Silberschatz,KorthandSudarshan
ExampleQuery
s Findthenamesofallbranchesthathavegreaterassetsthanall
brancheslocatedinBrooklyn.
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
(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
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
ExampleQuery
s FindallcustomerswhohaveatleasttwoaccountsatthePerryridge
branch.
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
DerivedRelations
s SQLallowsasubqueryexpressiontobeusedinthefromclause s Findtheaverageaccountbalanceofthosebrancheswheretheaverage
accountbalanceisgreaterthan$1200.
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
WithClause
s Thewithclauseprovidesawayofdefiningatemporaryviewwhose
definitionisavailableonlytothequeryinwhichthewithclause occurs.
s Findallaccountswiththemaximumbalance
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
certainusers.
s Anyrelationthatisnotoftheconceptualmodelbutismadevisibletoa
userasavirtualrelationiscalledaview.
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
ViewDefinition
s Aviewisdefinedusingthecreateviewstatementwhichhasthe
form
virtualrelationthattheviewgenerates.
s Whenaviewiscreated,thequeryexpressionisstoredinthe
database;theexpressionissubstitutedintoqueriesusingtheview.
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
ExampleQueries
s Aviewconsistingofbranchesandtheircustomers
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
terminate
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
ModificationoftheDatabaseDeletion
s DeleteallaccounttuplesatthePerryridgebranch
deletefromaccount wherebranch_name='Perryridge'
s DeleteallaccountsateverybranchlocatedinthecityNeedham.
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
ExampleQuery
s Deletetherecordofallaccountswithbalancesbelowtheaverageat
thebank.
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
ModificationoftheDatabaseInsertion
s Addanewtupletoaccount
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
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
ModificationoftheDatabaseUpdates
s Increaseallaccountswithbalancesover$10,000by6%,allother
accountsreceive5%.
q
q q
Theorderisimportant Canbedonebetterusingthecasestatement(nextslide)
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
CaseStatementforConditionalUpdates
s Samequeryasbefore:Increaseallaccountswithbalancesover
$10,000by6%,allotheraccountsreceive5%.
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
UpdateofaView
s Createaviewofallloandataintheloanrelation,hidingtheamount
attribute
DatabaseSystemConcepts,5thEd.,June2006
3.<number>
Silberschatz,KorthandSudarshan
UpdatesThroughViews(Cont.)
s Someupdatesthroughviewsareimpossibletotranslateinto
updatesonthedatabaserelations
q
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)
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