SQL: Queries, Programming, Triggers - University Of Wisconsin-Madison

Transcription

SQL: Queries, Programming,TriggersChapter 5Database Management Systems 3ed, R. Ramakrishnan and J. GehrkeR11sid biddayExample Instances 22 101 10/10/9658We will use theseinstances of theSailors andReserves relationsin our examples.If the key for theReserves relationcontained only theattributes sid andbid, how would thesemantics differ?103 11/12/96S1sid223158sname rating agedustin745.0lubber855.5rusty10 35.0S2sid28314458sname rating ageyuppy935.0lubber855.5guppy535.0rusty10 35.0Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke Basic SQL QuerySELECTFROMWHERE2[DISTINCT] target-listrelation-listqualificationrelation-list A list of relation names (possibly with arange-variable after each name).target-list A list of attributes of relations in relation-listqualification Comparisons (Attr op const or Attr1 opAttr2, where op is one of , , , , , )combined using AND, OR and NOT.DISTINCT is an optional keyword indicating that theanswer should not contain duplicates. Default is thatduplicates are not eliminated!Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke3

Conceptual Evaluation StrategySemantics of an SQL query defined in terms of thefollowing conceptual evaluation strategy: Compute the cross-product of relation-list.Discard resulting tuples if they fail qualifications.Delete attributes that are not in target-list.If DISTINCT is specified, eliminate duplicate rows. This strategy is probably the least efficient way tocompute a query! An optimizer will find moreefficient strategies to compute the same answers.Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke4Example of Conceptual EvaluationS.snameSailors S, Reserves RWHERE S.sid R.sid AND R.bid 103SELECTFROM(sid) sname rating age(sid) bid day22 dustin745.022101 10/10/9622 dustin745.058103 11/12/9631 lubber855.522101 10/10/9631 lubber855.558103 11/12/9658 rusty1035.022101 10/10/9658 rusty1035.058103 11/12/96Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke5A Note on Range Variables ORReally needed only if the same relationappears twice in the FROM clause. Theprevious query can also be written as:SELECTFROMWHERES.snameSailors S, Reserves RS.sid R.sid AND bid 103SELECTFROMWHEREsnameSailors, ReservesSailors.sid Reserves.sidAND bid 103Database Management Systems 3ed, R. Ramakrishnan and J. GehrkeIt is good style,however, to userange variablesalways!6

Find sailors who’ve reserved at least one boatSELECT S.sidFROM Sailors S, ReservesWHERE S.sid R.sid RWould adding DISTINCT to this query make adifference?What is the effect of replacing S.sid by S.sname inthe SELECT clause? Would adding DISTINCT tothis variant of the query make a difference?Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke7Expressions and StringsSELECT S.age, age1 S.age-5, 2*S.age ASFROM Sailors SWHERE S.sname LIKE ‘B %B’ age2Illustrates use of arithmetic expressions and stringpattern matching: Find triples (of ages of sailors andtwo fields defined by expressions) for sailors whose namesbegin and end with B and contain at least three characters.AS and are two ways to name fields in result.LIKE is used for string matching. ’ stands for anyone character and %’ stands for 0 or more arbitrarycharacters.Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke8Find sid’s of sailors who’ve reserved a red or a green boatUNION: Can be used tocompute the union of anytwo union-compatible sets oftuples (which arethemselves the result ofSQL queries).If we replace OR by AND inthe first version, what dowe get?Also available: EXCEPT(What do we get if wereplace UNION by EXCEPT?)SELECT S.sidFROM Sailors S, Boats B, Reserves RWHERE S.sid R.sid AND R.bid B.bidAND (B.color ‘red’ OR B.color ‘green’)SELECT S.sidFROM Sailors S, Boats B, Reserves RWHERE S.sid R.sid AND R.bid B.bidAND B.color ‘red’UNIONSELECT S.sidFROM Sailors S, Boats B, Reserves RWHERE S.sid R.sid AND R.bid B.bidAND B.color ‘green’Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke9

Find sid’s of sailors who’ve reserved a red and a green boatSELECT S.sidFROM Sailors S, Boats B1, Reserves R1,INTERSECT:Can be used toBoats B2, Reserves R2compute the intersection WHERE S.sid R1.sid AND R1.bid B1.bidAND S.sid R2.sid AND R2.bid B2.bidof any two unionAND (B1.color ‘red’ AND B2.color ‘green’)compatible sets of tuples.Key field!Included in the SQL/92SELECT S.sidFROM Sailors S, Boats B, Reserves Rstandard, but someWHERE S.sid R.sid AND R.bid B.bidsystems don’t support it.AND B.color ‘red’Contrast symmetry of theINTERSECTSELECT S.sidUNION and INTERSECTFROM Sailors S, Boats B, Reserves Rqueries with how muchWHERE S.sid R.sid AND R.bid B.bidthe other versions differ.AND B.color ‘green’Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke10Nested QueriesFind names of sailors who’ve reserved boat # 103:SELECT S.snameFROM Sailors SWHERE S.sid IN (SELECT R.sidFROM ReservesRR.bid 103)A very powerful feature of SQL: a WHERE clause canitself contain an SQL query! (Actually, so can FROMand HAVING clauses.)WHERE To find sailors who’ve not reserved # 103, use NOT IN.To understand semantics of nested queries, think of anested loops evaluation: For each Sailors tuple, check thequalification by computing the subquery.Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke11Nested Queries with CorrelationFind names of sailors who’ve reserved boat # 103:SELECT S.snameFROM Sailors SWHERE EXISTS (SELECT *FROM Reserves RWHERE R.bid 103 ANDS.sid R.sid) EXISTS is another set comparison operator, like IN.If UNIQUE is used, and * is replaced by R.bid, findssailors with at most one reservation for boat # 103.(UNIQUE checks for duplicate tuples; * denotes allattributes. Why do we have to replace * by R.bid?)Illustrates why, in general, subquery must be recomputed for each Sailors tuple.Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke12

More on Set-Comparison Operators We’ve already seen IN, EXISTS and UNIQUE. Can alsouse NOT IN, NOT EXISTS and NOT UNIQUE.Also available: op ANY, op ALL, op IN , , , , , Find sailors whose rating is greater than that of somesailor called Horatio:SELECT *FROM Sailors SWHERE S.rating ANY (SELECT S2.ratingFROM Sailors S2WHERE S2.sname ‘Horatio’)Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke13Rewriting INTERSECT Queries Using INFind sid’s of sailors who’ve reserved both a red and a green boat:SELECT S.sidFROM Sailors WHERES, Boats B, Reserves RS.sid R.sid AND R.bid B.bid AND B.color ‘red’AND S.sid IN (SELECT S2.sidFROM Sailors S2, Boats B2, Reserves R2WHERE S2.sid R2.sid AND R2.bid B2.bidAND B2.color ‘green’)Similarly, EXCEPT queries re-written using NOT IN.To find names (not sid’s) of Sailors who’ve reservedboth red and green boats, just replace S.sid by S.snamein SELECT clause. (What about INTERSECT query?)Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke(1)Division in SQLFind sailors who’ve reserved all boats. Let’s do it the hardway, without EXCEPT:14SELECT S.snameFROM Sailors SWHERE NOT EXISTS((SELECT B.bidFROM Boats B)EXCEPT(SELECT R.bidFROM Reserves RWHERE R.sid S.sid))(2) SELECT S.snameFROM Sailors SWHERE NOT EXISTS (SELECT B.bidFROM Boats BWHERE NOT EXISTS (SELECT R.bidSailors S such that .FROM Reserves RWHERE R.bid B.bidthere is no boat B without .AND R.sid S.sid))a Reserves tuple showing S reserved BDatabase Management Systems 3ed, R. Ramakrishnan and J. Gehrke15

Aggregate OperatorsSignificant extension ofrelational algebra. SELECT COUNT (*)FROM Sailors SSELECT AVG (S.age)FROM Sailors SWHERECOUNT (*)COUNT ( [DISTINCT] A)SUM ( [DISTINCT] A)AVG ( [DISTINCT] A)MAX (A)MIN (A)single columnSELECT S.snameFROM Sailors SWHERE S.rating (SELECT MAX(S2.rating)FROM Sailors S2)S.rating 10SELECT COUNT (DISTINCTFROM Sailors SWHERE S.sname ‘Bob’S.rating) SELECT AVG ( DISTINCT S.age)FROM Sailors SWHERE S.rating 10Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke16 Find name and age of the oldest sailor(s)The first query is illegal!(We’ll look into thereason a bit later, whenwe discuss GROUP BY.)The third query isequivalent to the secondquery, and is allowed inthe SQL/92 standard,but is not supported insome systems.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.ageDatabase Management Systems 3ed, R. Ramakrishnan and J. Gehrke17GROUP BY and HAVING So far, we’ve applied aggregate operators to all(qualifying) tuples. Sometimes, we want to applythem to each of several groups of tuples.Consider: Find the age of the youngest sailor for eachrating level.In general, we don’t know how many rating levelsexist, and what the rating values for these levels are!Suppose we know that rating values go from 1 to 10;we can write 10 queries that look like this (!):SELECT MIN (S.age)FROM Sailors SS.rating iDatabase Management Systems 3ed, R. Ramakrishnan and WHEREJ. GehrkeFor i 1, 2, . , 10:18

Queries With GROUP BY and HAVINGSELECT[DISTINCT] P BY grouping-listHAVINGgroup-qualificationThe target-list contains (i) attribute names (ii) termswith aggregate operations (e.g., MIN (S.age)). The attribute list (i) must be a subset of grouping-list.Intuitively, each answer tuple corresponds to a group, andthese attributes must have a single value per group. (Agroup is a set of tuples that have the same value for allattributes in grouping-list.)Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke19Conceptual EvaluationThe cross-product of relation-list is computed, tuplesthat fail qualification are discarded, unnecessary’ fieldsare deleted, and the remaining tuples are partitionedinto groups by the value of attributes in grouping-list.The group-qualification is then applied to eliminatesome groups. Expressions in group-qualification musthave a single value per group! In effect, an attribute in group-qualification that is not anargument of an aggregate op also appears in grouping-list.(SQL does not exploit primary key semantics here!)One answer tuple is generated per qualifying group.Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke20Find the age of the youngest sailor with age 18,for each rating with at least 2 such sailorssid sname rating age22 dustin745.031 lubber855.5WHERE S.age 1871 zorba10 16.0GROUP BY S.rating64 horatio735.0HAVING COUNT (*) 129 brutus133.0Only S.rating and S.age are58 rusty10 35.0mentioned in the SELECT,rating ageGROUP BY or HAVING clauses;133.0other attributes unnecessary’.rating745.02nd column of result is735.0735.0unnamed. (Use AS to name it.)855.5Answerrelation10 35.0Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke21SELECT S.rating, MIN (S.age)FROM Sailors S

For each red boat, find the number ofreservations for this boatSELECT B.bid, COUNT (*) AS scountFROM Sailors S, Boats B, Reserves RWHERE S.sid R.sid ANDGROUP BY B.bid R.bid B.bid AND B.color ‘red’Grouping over a join of three relations.What do we get if we remove B.color ‘red’from the WHERE clause and add a HAVINGclause with this condition?What if we drop Sailors and the conditioninvolving S.sid?Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke22Find the age of the youngest sailor with age 18,for each rating with at least 2 sailors (of any age)SELECT S.rating, MIN (S.age)FROM Sailors SWHERE S.age 18GROUP BY S.ratingHAVING 1 (SELECT COUNT (*)FROM Sailors S2WHERE S.rating S2.rating)Shows HAVING clause can also contain a subquery.Compare this with the query where we consideredonly ratings with 2 sailors over 18!What if HAVING clause is replaced by: HAVING COUNT(*) 1Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke23Find those ratings for which the averageage is the minimum over all ratingsAggregate operations cannot be nested! WRONG: SELECT S.ratingFROM Sailors SWHERE S.age (SELECT MIN (AVG (S2.age)) FROMvSailors S2)Correct solution (in SQL/92):SELECT Temp.rating, Temp.avgageFROM (SELECT S.rating, AVG (S.age) ASavgageFROM Sailors SGROUP BY S.rating) AS TempWHERE Temp.avgage (SELECT MIN (Temp.avgage)FROM Temp)Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke24

Null ValuesField values in a tuple are sometimes unknown (e.g., arating has not been assigned) or inapplicable (e.g., nospouse’s name). SQL provides a special value null for such situations.The presence of null complicates many issues. E.g.: Special operators needed to check if value is/is not null.Is rating 8 true or false when rating is equal to null? Whatabout AND, OR and NOT connectives?We need a 3-valued logic (true, false and unknown).Meaning of constructs must be defined carefully. (e.g.,WHERE clause eliminates rows that don’t evaluate to true.)New operators (in particular, outer joins) possible/needed.Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke25Integrity Constraints (Review)An IC describes conditions that every legal instanceof a relation must satisfy. Inserts/deletes/updates that violate IC’s are disallowed.Can be used to ensure application semantics (e.g., sid is akey), or prevent inconsistencies (e.g., sname has to be astring, age must be 200) Types of IC’s: Domain constraints, primary keyconstraints, foreign key constraints, generalconstraints.Domain constraints: Field values must be of right type.Always enforced.Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke26CREATE TABLE Sailors( sid INTEGER,sname CHAR(10),rating INTEGER,age REAL,PRIMARY KEY (sid),CHECK ( rating 1AND rating CREATE TABLE Reserves( sname CHAR(10),bid INTEGER,day DATE,PRIMARY KEY (bid,day),CONSTRAINT noInterlakeResCHECK ( Interlake’ General Constraints Useful whenmore generalICs than keysare involved.Can use queriesto expressconstraint.Constraints canbe named.Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke( SELECT B.bnameFROM Boats BWHERE B.bid bid)))10 )27

Constraints Over Multiple Relations CREATE TABLE Sailors( sid INTEGER,Number of boatssname CHAR(10),plus number ofAwkward and rating INTEGER,sailors is 100wrong!age REAL,If Sailors isPRIMARY KEY (sid),empty, theCHECKnumber of Boats( (SELECT COUNT (S.sid) FROM Sailors S)tuples can be (SELECT COUNT (B.bid) FROM Boats B) anything!100 )is theCREATE ASSERTION smallClubright solution;CHECKnot associatedwith either table. ( (SELECT COUNT (S.sid) FROM Sailors S) (SELECT COUNT (B.bid) FROM Boats B) 100 )ASSERTIONDatabase Management Systems 3ed, R. Ramakrishnan and J. Gehrke28Triggers Trigger: procedure that starts automatically ifspecified changes occur to the DBMSThree parts:Event (activates the trigger)Condition (tests whether the triggers should run)Action (what happens if the trigger runs)Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke29Triggers: Example (SQL:1999)CREATE TRIGGER youngSailorUpdateAFTER INSERT ON SAILORSREFERENCING NEW TABLE NewSailorsFOR EACH STATEMENTINSERTINTO YoungSailors(sid, name, age, rating)SELECT sid, name, age, ratingFROM NewSailors NWHERE N.age 18Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke30

SummarySQL was an important factor in the early acceptanceof the relational model; more natural than earlier,procedural query languages.Relationally complete; in fact, significantly moreexpressive power than relational algebra.Even queries that can be expressed in RA can oftenbe expressed more naturally in SQL.Many alternative ways to write a query; optimizershould look for most efficient evaluation plan. In practice, users need to be aware of how queries areoptimized and evaluated for best results.Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke31Summary (Contd.) NULL for unknown field values brings manycomplicationsSQL allows specification of rich integrityconstraintsTriggers respond to changes in the databaseDatabase Management Systems 3ed, R. Ramakrishnan and J. Gehrke32

SQL: Queries, Programming, Triggers Chapter 5 Database Management Systems 3ed, R. Ramakrishnan and J. Gehrke 2 Example Instances sid sname rating age 22 dustin 7 45.0 31 lubber 8 55.5 58 rusty 10 35.0 sid sname rating age 28 yuppy 9 35.0 31 lubber 8 55.5 44 guppy 5 35.0 58 rusty 10 35.0 sid bid day 22 101 10/10/96 58 103 11/12/96 R1 S1 S2 We .