SQL:Queries,Programming,Triggers
Chapter5,CowBookor
Seehttp://sqlzoo.net/
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 1
SQLLanguage
• DDL:Datadefinitionlanguage• DML:Datamanipulationlanguage• EmbeddedandDynamicSQL• Triggers• Security• TransactionManagement• RemoteDatabaseaccess
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 2
BasicSQLQuery
• Semantics/Conceptualevaluationstrategy:– Computethecross-productofrelation-list.– Discardresultingtuplesiftheyfailqualifications.– Deleteattributesthatarenotintarget-list.– IfDISTINCTisspecified,eliminateduplicaterows.
• Notanefficientevaluationplan!(Optimzier picksefficientplans)
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 3
SELECT [DISTINCT] target-listFROM relation-listWHERE qualification
Optional
List of relations
Attr1 op Attr2 OPS: <, >, =, <=, >=, <>
Combine using AND, OR, NOT
Attributes from input relations
ExampleofConceptualEvaluation
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 4
SELECT S.name, A.hours FROM Senators S, Attendance A WHERE S.ssn = A.ssn and A.date = ‘24-Sept-2016’
ssn name email age income
11-111 Bob [email protected] 51 100.122-222 Jane [email protected] 54 130.133-333 Jane [email protected] 51 99.8
ssn date hours
11-111 12-Aug-2016 1.133-333 24-Sept-2016 4.1
(ssn) name email age income (ssn) date hours
11-111 Bob [email protected] 51 100.1 11-111 12-Aug-2016 1.1
33-333 24-Sept-2016 4.111-111 Bob [email protected] 51 100.1
22-222 Jane [email protected] 54 130.1 33-333 24-Sept-2016 4.1
33-333 Jane [email protected] 51 99.8 33-333 24-Sept-2016 4.1
22-222 Jane [email protected] 54 130.1 11-111 12-Aug-2016 1.1
33-333 Jane [email protected] 51 99.8 11-111 12-Aug-2016 1.1
33-333 Jane [email protected] 51 99.8 33-333 24-Sept-2016 4.1
Findsenatorswhoattendedthe‘24-Sept-2016’session
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 5
SELECT S.nameFROM Senators S, Attendance A WHERE S.ssn = A.ssn and date = ‘24-Sept-2016’
n Add DISTINCT to this query. Effect?n Replace S.name by S.ssn.
Effect of adding DISTINCT to this query
RA: pname (sdate=‘24-Sept-2016’(Senators wv Attendance))
n Equivalent SQL?n What is the schema of Senators ⋈ Attendance?
ANoteonRangeVariables• Neededonlyifthesamerelationappearstwiceinthe
FROM clause.
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 6
SELECT S.name, A.hoursFROM Senators S, Attendance A WHERE S.ssn = A.ssn and A.date = ‘24-Sept-2016’
It is good style,however, to always userange variables!
ORSELECT Senators.name, Attendance.hoursFROM Senators , Attendance WHERE Senators.ssn = Attendance.ssn and
Attendance.date = ‘24-Sept-2016’
ExpressionsandStrings
• Illustratesuseofarithmeticexpressionsandstringpatternmatching
• AS and= aretwowaystonamefieldsinresult.• LIKE isusedforstringmatching.`_’standsforanyonecharacter
and`%’standsfor0ormorearbitrarycharacters.• Collation:sortorderforcharactersets
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 7
SELECT S.name, S.age, age1=S.age+2, S.income/S.age AS iarFROM Senators SWHERE S.sname LIKE ‘Ja_%Doe’ORDER BY S.name
Findsenatorswhoattendedeitherthe‘24-Sept-2016’or‘25-Sept-2016’session
• UNION:Computetheunionoftwounion-compatible setsoftuples– Samenumber/typesoffields.
• Alsoavailable:INTERSECTandEXCEPT (WhatdowegetifwereplaceUNION byEXCEPT?)
• SQLoddities:duplicateswithunion,except,intersect– Default:eliminateduplicates!– UseALLtokeepduplicates
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 8
SELECT S.ssnFROM Senators S, Attendance AWHERE S.ssn = A.ssnand (A.date = ‘24-Sept-2016’ or
A.date = ‘25-Sept-2016’)
SELECT S.ssnFROM Senators S, Attendance AWHERE S.ssn = A.ssnand A.date = ‘24-Sept-2016’UNIONSELECT S.ssnFROM Senators S, Attendance AWHERE S.ssn = A.ssnand A.date = ‘25-Sept-2016’
• INTERSECT:Computetheintersectionofanytwounion-compatible setsoftuples.
• IntheSQL/92standard,butsomesystemsdon’tsupportit.
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 9
SELECT S.ssn, S.nameFROM Senators S, Attendance AWHERE S.ssn = A.ssnand A.date = ‘24-Sept-2016’ INTERSECTSELECT S.ssn, S.nameFROM Senators S, Attendance AWHERE S.ssn = A.ssnand A.date = ‘25-Sept-2016’
Find senators who attended both the ‘24-Sept-2016’ and ‘25-Sept-2016’ session
SELECT S.ssnFROM Senators S, Attendance A1,
Attendance A2WHERE S.ssn = A1.ssn and S.ssn = A2.ssnand A1.date = ‘24-Sept-2016’ and A2.date = ‘25-Sept-2016’
Key field! What happens if S.name is used
NestedQueries
• PowerfulfeatureofSQL– WHERE clausecanitselfcontainanSQLquery!– Actually,socanFROM andHAVING clauses
• Tofindsailorswho’venot reserved#103,useNOTIN• ConceptualEvaluation: nestedloops ForeachSailorstuple,check
thequalificationbycomputingthesubquery.
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 10
SELECT S.snameFROM Sailors SWHERE S.sid IN (SELECT R.sid
FROM Reserves RWHERE R.bid=103)
Find names of sailors who’ve reserved boat #103
Can you rewrite this to not use a nested query?
Sailors (sid, sname, rating, age)Reserves (sid, bid, day)Boats (bid, bname, color)
NestedQuerieswithCorrelation
• UNIQUE returnstrueiftherowappearsonlyonce
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 11
Find names of sailors who’ve reserved boat #103
SELECT S.snameFROM Sailors SWHERE EXISTS (SELECT *
FROM Reserves RWHERE R.bid=103 AND S.sid=R.sid)
SELECT S.snameFROM Sailors SWHERE EXISTS (SELECT UNIQUE R.bid
FROM Reserves RWHERE R.bid=103 AND S.sid=R.sid)Why R.bid?
n Illustrates why, in general, subquery must be re-computed for each Sailors tuple.
n EXISTS tests if the set is not empty
------------------------------------------------------------------Find names of sailors with exactly one reservation for boat #103
MoreonSet-ComparisonOperators• We’vealreadyseenIN,EXISTSandUNIQUE.Canalsouse
NOTIN,NOTEXISTSandNOTUNIQUE.• Alsoavailable:op ANY,op ALL,opis<,≤,>,≥,=,≠
• FindsailorswhoseratingisgreaterthanthatofsomesailorcalledHoratio:
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 12
(SELECT *FROM Sailors SWHERE S.ratin)> ANY (SELECT S2.rating
FROM Sailors S2WHERE S2.sname=‘Horatio’)
SELECT *FROM Sailors SWHERE S.rating > ANY (SELECT S2.rating
FROM Sailors S2WHERE S2.sname=‘Horatio’)
• Similarly,INTERSECT queriesre-writtenusingIN.
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 13
Find sailors (sid) who’ve reserved some boat for ‘24-Sept-2016’ but have no reservations for ‘09-Oct-2016’
SELECT S.sidFROM Sailors S, Reserves RWHERE S.sid=R.sid
AND R.day=‘24-Sept-2016’AND S.sid NOT IN
(SELECT S2.sidFROM Sailors S2, Reserves R2WHERE S2.sid=R2.sid AND R2.day=‘‘09-Oct-2016’)
Sailors (sid, sname, rating, age)Reserves (sid, bid, day)Boats (bid, bname, color)
SELECT S.sidFROM Sailors S, Reserves RWHERE S.sid=R.sid
AND R.day=‘24-Sept-2016’EXCEPT(SELECT S2.sidFROM Sailors S2, Reserves R2WHERE S2.sid=R2.sid
AND R2.day=‘‘09-Oct-2016’)
Rewriting ExceptQueries Using NOT IN
DivisioninSQL
WithoutEXCEPT:
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 14
Find sailors who’ve reserved all boats.
SELECT S.snameFROM Sailors SWHERE NOT EXISTS
((SELECT B.bidFROM Boats B)
EXCEPT(SELECT R.bidFROM Reserves RWHERE R.sid=S.sid))
(1)
SELECT S.snameFROM Sailors SWHERE NOT EXISTS (SELECT B.bid
FROM Boats B WHERE NOT EXISTS (SELECT R.bid
FROM Reserves RWHERE R.bid=B.bid
AND R.sid=S.sid))
(2)
Sailors S such that ...
there is no boat B without ...
a Reserves tuple showing S reserved B
Sailors (sid, sname, rating, age)Reserves (sid, bid, day)Boats (bid, bname, color)
AggregateOperators
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 15
COUNT (*)COUNT ( [DISTINCT] A)SUM ( [DISTINCT] A)AVG ( [DISTINCT] A)MAX (A) Can use DistinctMIN (A) Can use Distinct
SELECT AVG (S.age)FROM Sailors SWHERE S.rating=10
SELECT COUNT (*) FROM Sailors S
SELECT AVG ( DISTINCT S.age)FROM Sailors SWHERE S.rating=10
SELECT S.sname FROM Sailors SWHERE S.rating= (SELECT MAX(S2.rating) FROM Sailors S2)
single column
SELECT COUNT (DISTINCT S.name)FROM Sailors S
Findname&ageoftheoldestsailor(s)
• Thefirstqueryisillegal!(waitforGROUPBY.)
• Q3isallowedintheSQL/92standard,butnotsupportedinsomesystems
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 16
SELECT S.sname, MAX (S.age)FROM Sailors SSELECT S.sname, S.ageFROM Sailors SWHERE S.age =
(SELECT MAX (S2.age)FROM Sailors S2)
SELECT S.sname, S.ageFROM Sailors SWHERE (SELECT MAX (S2.age)
FROM Sailors S2)= S.age
How many tuples in the result?
GROUPBYandHAVING• Applyaggregatetoeachofseveralgroups oftuples• Findtheageoftheyoungestsailorforeachratinglevel
– Don’tknow:#ratinglevels,andratingvalues– Supposewedidknowthatratingvaluesgofrom1to10
• wecanwrite10queriesthatlooklikethis(!):
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 17
SELECT MIN (S.age)FROM Sailors SWHERE S.rating = i
For i = 1, 2, ... , 10:SELECT MIN (S.age), S.ratingFROM Sailors SGROUP BY S.rating
QueriesWithGROUPBYandHAVING
• The target-listcontains– Attributenames:mustbeasubsetofgrouping-list.– Termswithaggregateoperations(e.g.,MIN(S.age)).
• Thegroup-qualification– Musthaveasinglevaluepergroup
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 18
SELECT [DISTINCT] target-listFROM relation-listWHERE qualificationGROUP BY grouping-listHAVING group-qualification
How many tuples in the result?
ConceptualEvaluation• Cross-product->discardtuples->applyprojection
->partitionintogroupsusingthegrouping-list attributevalues->eliminategroupsthatdon’tsatisfythegroup-qualification
• Expressionsingroup-qualification haveasinglevaluepergroup!– Ineffect,anattributeingroup-qualification thatisnotanargumentofanaggregateopalsoappearsingrouping-list.(SQLdoesnotexploitprimarykeysemanticshere!)
• Oneanswertupleisgeneratedperqualifyinggroup.
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 19
Findtheageoftheyoungestsailorwithage>=18,foreachratingwithatleast2such sailors
• 2ndcolumnofresultisunnamed.(UseAS tonameit)
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 20
SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age >= 18GROUP BY S.ratingHAVING COUNT (*) > 1
sid sname rating age 22 dustin 7 45.0 31 lubber 8 55.5 71 zorba 10 16.0 64 horatio 7 35.0 29 brutus 1 33.0 58 rusty 10 35.0
rating age 1 33.0 7 45.0 7 35.0 8 55.5 10 35.0
rating 7 35.0
Answer relation
rating
Foreachredboat,findthenumberofreservationsforthisboat
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 21
SELECT B.bid, COUNT (*) AS scountFROM Sailors S, Boats B, Reserves RWHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’GROUP BY B.bid
SELECT B.bid, COUNT (*) AS scountFROM Sailors S, Boats B, Reserves RWHERE S.sid=R.sid AND R.bid=B.bidGROUP BY B.bid Would this work?HAVING B.color = ‘red’ note: one color per bid
Findtheageoftheyoungestsailorwithage>18,foreachratingwithatleast2sailors(ofanyage)
• SubqueryintheHAVING clause• Comparethiswiththequerywhereweconsideredonlyratingswith2sailorsover18!
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 22
SELECT S.rating, MIN (S.age) AS MINAGEFROM Sailors SWHERE S.age > 18GROUP BY S.ratingHAVING 1 < (SELECT COUNT (*) FROM Sailors S2
WHERE S.rating=S2.rating)
Findratingsforwhichtheaverageageistheminimumoftheaverageageoverallratings
• Aggregateoperationscannotbenested!WRONG:
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 23
SELECT S.ratingFROM Sailors SWHERE AVG(S.age) =
(SELECT MIN (AVG (S2.age)) FROM Sailors S2)
SELECT Temp.rating, Temp.avgageFROM (SELECT S.rating, AVG (S.age) AS avgage
FROM Sailors SGROUP BY S.rating) AS Temp
WHERE Temp.avgage = (SELECT MIN (Temp.avgage) FROM Temp)
§ Correct solution (in SQL/92):
NullValues• Represent
– unknown (e.g.,ratingnotassigned)or– inapplicable (e.g.,nospouse’sname)
• Complicationswithnulls:– Operatorstocheckifvalueis/isnotnull.– Israting>8 trueorfalsewhenrating isnull?
• Answer:Evaluatetounknown
– WhataboutAND,ORandNOT connectives?• Need3-valuedlogic (true,falseandunknown)
– Notunknown=unknown
– WHEREclauseeliminatesrowsthatdon’tevaluatetotrue– Newoperators(inparticular,outerjoins)possible/needed.
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 24
p q p AND q p OR q
T T T TT F F TT U U TF T F TF F F FF U F UU T U TU F F UU U U U
OuterJoin
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 25
sid bid day 22 101 10/10/99
Reservessid sname rating age 22 dustin 7 45.0 58 rusty 10 35.0
Sailors
Select S.sid, R.bidFrom Sailors S NATURAL LEFT OUTER JOIN Reserves R
sid bid 22 101 58 null
Result Similarly:• RIGHT OUTER JOIN• FULL OUTER JOIN
EmbeddedSQL
• CallSQLcommandsfromahostlanguage(e.g.,C)program.– SQLstatementscanrefertohostvariables(includingspecialvariablesusedtoreturnstatus).
– Mustincludeastatementtoconnect totherightdatabase.
• SQLrelationsare(multi-)setsofrecords,withnoaprioriboundonthenumberofrecords.NosuchdatastructureinC.– SQLsupportsamechanismcalledacursor tohandlethis.
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 26
Cursors• Candeclareacursoronarelationorquerystatement(whichgeneratesarelation).
• Canopen acursor,andrepeatedlyfetch atuple thenmove thecursor,untilalltuples havebeenretrieved.– Specialclause,calledORDERBY,incursorqueriestocontroltheorderinwhichtuples arereturned.
– FieldsinORDERBYmustalsoappearinSELECTclause.
• Canalsomodify/deletetuple pointedtobyacursor
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 27
Cursorthatgetsnamesofsailorswho’vereservedaredboat,inalphabeticalorder
• CanwereplaceS.sname byS.sid intheORDERBYclause!– EverycolumnintheORDERBYclausemustappearintheSELECT
clause
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 28
EXEC SQL DECLARE sinfo CURSOR FORSELECT S.snameFROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ORDER BY S.sname
IntegrityConstraints• AnICdescribesconditionsthateverylegalinstanceofarelationmust
satisfy.– Inserts/deletes/updatesthatviolateIC’saredisallowed.
• TypesofIC’s:Domainconstraints,primarykeyconstraints,foreignkeyconstraints,generalconstraints.
• Cancreatenewdomains,DomainConstraints:– CREATEDOMAINLegalRatingsINTEGERDEFAULT0
CHECK(VALUE>=1andVALUE<=10)– CreateTableSailor(…,ratingLegalRatings,…)– UnderlyingdomainisstillIntegersforcomparison
• Cancreatenewtypes:CREATETYPEAllRatingsasINTEGER– Underlyingdomainisnowanewtype.Can’tcomparewithINTEGERwithouta
cast.NoneoftheaggregatesonINTEGERworkonAllRatings
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 29
TableConstraints• MoregeneralICsthan
keyconstraints• Canusequeries
toexpressconstraint
• Constraintscanbenamed.
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 30
CREATE TABLE Sailors( sid INTEGER,sname CHAR(10),rating INTEGER,age REAL,PRIMARY KEY (sid),CHECK ( rating >= 1
AND rating <= 10 )CREATE TABLE Reserves( sname CHAR(10),bid INTEGER,day DATE,PRIMARY KEY (bid,day),CONSTRAINT noInterlakeResCHECK (`Interlake’ <>
( SELECT B.bnameFROM Boats BWHERE B.bid=bid)))
ConstraintsOverMultipleRelations• Awkward
&Wrong!• IfSailorsisempty,
thenumberofBoatstuplescanbeanything!
• ASSERTION istherightsolution;notassociatedwitheithertable
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 31
CREATE TABLE Sailors( sid INTEGER,sname CHAR(10),rating INTEGER,age REAL,PRIMARY KEY (sid),CHECK ((SELECT COUNT (S.sid) FROM Sailors S) +(SELECT COUNT (B.bid) FROM Boats B) < 100)
CREATE ASSERTION smallClubCHECK((SELECT COUNT (S.sid) FROM Sailors S) +
(SELECT COUNT (B.bid) FROM Boats B) < 100)
Number of boatsplus number of sailors is < 100
Triggers• Trigger:procedurethatstartsautomaticallyifspecifiedchangesoccurtotheDBMS
• Threeparts:– Event(activatesthetrigger)– Condition(testswhetherthetriggersshouldrun)– Action(whathappensifthetriggerruns)
• BeforeandAfterTriggers
• TriggerExecution– Row-levelTriggers:Onceperrow– Statement-levelTriggers:OnceperSQLstatement
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 32
Triggers:ExampleCREATETRIGGERinit_countBEFOREINSERTONStudents/*Event*/
DECLAREcountINTEGER /*Action*/BEGINcount:=0END
CREATETRIGGERincr_countAFTERINSERTONStudent/*Event*/WHEN(new.age<18) /*Condition*/FOREACHROWBEGIN /*Action*/count:=count+1;END
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 33
Triggers• Firsttriggerexecutedbefore theactivatingstatement,second
executesafter theactivatingstatement.• Options:
– “BEFORE”– “AFTER”– “INSTEADOF” (onlyvalidonviews)
• Incombinationwith:– “FOREACHROW”- executeoncepermodifiedrecord– (default)- executeonceperactivatingstatement.
Canalsospecifyusing“FOREACHSTATEMENT”• Incombinationwith:
– “INSERT”– “DELETE”– “UPDATE”
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 34
Triggers• Referringtovalues
– Old– New– Setofchangedrecord
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 35
Triggers:ExampleCREATETRIGGERyoungSailorUpdate
AFTERINSERTONSAILORSREFERENCINGNEWTABLENewSailorsFOREACHSTATEMENT
INSERTINTOYoungSailors(sid,name,age,rating)SELECTsid,name,age,ratingFROMNewSailorsNWHEREN.age<=18
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 36
Triggersv/sConstraints• Oftenusedtomaintainconsistency
– Canyouuseaforeignkey?– Foreignkeysarenotdefinedoperationally
• Constraintsareeasiertounderstandthantriggers• Triggersaremorepowerful.
– Oftenusedtofilloutfieldsinaform– Checkcomplexactions(suchascreditlimitinashoppingapplication)
– Checkpreferredcustomerstatus– Generatelogsforauditingandsecuritychecks.– InternallycanbeusedbytheDBMSforreplicationmanagement.
3/25/17 CS 564: Database Management Systems, Jignesh M. Patel 37
Top Related