Download presentation
Presentation is loading. Please wait.
Published byBlaise Spencer Modified over 9 years ago
1
Database Management Systems, R. Ramakrishnan and J. Gehrke1 SQL: Queries, Programming, Triggers Chapter 5
2
Database Management Systems, R. Ramakrishnan and J. Gehrke2 Basic SQL Query relation-list A list of relation names target-list A list of attributes of relations in relation-list qualification Comparisons (“Attr op const” or “Attr1 op Attr2,” where op is one of ˂, ˃, ≤, ≥, =, ≠ ) combined using AND, OR, and NOT. DISTINCT is an optional keyword indicating that the answer should not contain duplicates. (Default: not eliminated) SELECT [DISTINCT] target-list FROM relation-list WHERE qualification
3
Database Management Systems, R. Ramakrishnan and J. Gehrke3 Querying Relations (1) SELECT S.name, E.cid FROM Students S, Enrolled E WHERE S.sid=E.sid AND E.grade=“A” Enrolled A student with “sid” has an entry in Enrolled The Enrolled entry has a grade of “A” What does the following query compute? sidnameloginagegpa 53831Zhangzhang@ee193.2 53650Smithsmith@cs213.9 53666Jonesjones@cs203.5 Students Retrieve names of students and the courses they received an “A” grade
4
Database Management Systems, R. Ramakrishnan and J. Gehrke4 Querying Relations (2) SELECT S.name, E.cid FROM Students S, Enrolled E WHERE S.sid=E.sid AND E.grade=“A” Enrolled sidnameloginagegpa 53831Zhangzhang@ee193.2 53650Smithsmith@cs213.9 53666Jonesjones@cs203.5 Students S.nameE.cid SmithTopology112
5
Database Management Systems, R. Ramakrishnan and J. Gehrke5 Example Schema We will use these table definitions in our subsequent examples. Sailors(sid: integer, sname: string, rating: integer, age: real) Boats(bid: integer, bname: string, color: string) Reserves(sid: integer, bid: integer, day: date) Make reservations
6
Database Management Systems, R. Ramakrishnan and J. Gehrke6 Example Instances R1 S1 S2 v We will use these instances of the Sailors and Reserves relations in our examples. v If the key for the Reserves relation contained only the attributes sid and bid, how would the semantics differ?
7
Database Management Systems, R. Ramakrishnan and J. Gehrke7 Projection Projection on sname and rating S2
8
Database Management Systems, R. Ramakrishnan and J. Gehrke8 Cross-Product R1 × S1 Each row of R1 is paired with each row of S1. R1 S1 Projection and cross-product are relational operators. We will discuss other operators in another chapter
9
Database Management Systems, R. Ramakrishnan and J. Gehrke9 Query Result Define search space Semantics of SQL SELECT [DISTINCT] target-list FROM relation-list WHERE qualification R1 × R2 × R3 × · · · Select rows qualification Select columns target-list relation-list Projection ˂, ˃, ≤, ≥, =, ≠ QUERY PROCESSOR
10
Database Management Systems, R. Ramakrishnan and J. Gehrke10 Conceptual Evaluation Strategy v Semantics of an SQL query defined in terms of the following 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. v This strategy is probably the least efficient way to compute a query! An optimizer will find more efficient strategies to compute the same answers.
11
Database Management Systems, R. Ramakrishnan and J. Gehrke11 Example of Conceptual Evaluation SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103 (sid)snameratingage(sid)bidday 22dustin745.02210110/10/96 22dustin745.05810311/12/96 31lubber855.52210110/10/96 31lubber855.55810311/12/96 58rusty1035.02210110/10/96 58rusty1035.05810311/12/96 S×R Answer
12
Database Management Systems, R. Ramakrishnan and J. Gehrke12 Example of Conceptual Evaluation SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103 (sid)snameratingage(sid)bidday 22dustin745.02210110/10/96 22dustin745.05810311/12/96 31lubber855.52210110/10/96 31lubber855.55810311/12/96 58rusty1035.02210110/10/96 58rusty1035.05810311/12/96 S×R
13
Database Management Systems, R. Ramakrishnan and J. Gehrke13 A Note on Range Variables Really needed only if the same relation appears twice in the FROM clause. The previous query can be written in two ways: SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND bid=103 SELECT sname FROM Sailors, Reserves WHERE Sailors.sid=Reserves.sid AND bid=103 It is good style, however, to use range variables always! OR Range variable
14
Database Management Systems, R. Ramakrishnan and J. Gehrke14 Find sailors who’ve reserved at least one boat Would adding DISTINCT to this query make a difference? Remove duplicate sid What is the effect of replacing S.sid by S.sname in the SELECT clause? Since two sailors may have the same name, some sailor may have no reservation even his/her name is in the output SELECT S.sid FROM Sailors S, Reserves R WHERE S.sid = R.sid
15
Database Management Systems, R. Ramakrishnan and J. Gehrke15 Find sailors who’ve reserved at least one boat SELECT S.sid FROM Sailors S, Reserves R WHERE S.sid = R.sid Given a sailor sid sid has a reservation Sailors(sid, sname, rating, age) Reserves(sid, bid, day) sid has a reservation
16
Database Management Systems, R. Ramakrishnan and J. Gehrke16 Name begins and ends with ‘B’ and contains at least three characters Arithmetic Expressions and Strings LIKE is used for string matching. ‘_ ’ stands for any one character and ‘%’ stands for 0 or more arbitrary characters. SELECT S.age, age1 = S.age-5, 2*S.age AS age2 FROM Sailors S WHERE S.sname LIKE ‘B_%B’ AS and = are two ways to name fields in result
17
Database Management Systems, R. Ramakrishnan and J. Gehrke17 Find names of sailors who’ve reserved a red or a green boat SELECT S.name FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND (B.color=‘red’ OR B.color=‘green’) Sailors(sid, sname, rating, age) Reserves(sid, bid, day) Boats(bid, bname, color) sid has a reservation for bid bid is a boat color = ‘red’ OR color = ‘green’
18
Database Management Systems, R. Ramakrishnan and J. Gehrke18 Find names of sailors who’ve reserved a red or a green boat UNION: Compute the union of any two union- compatible sets of tuples (which are themselves the result of SQL queries). SELECT S.name FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ UNION SELECT S.name FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘green’ Name of sailors who’ve reserved red boats Name of sailors who’ve reserved green boats
19
Database Management Systems, R. Ramakrishnan and J. Gehrke19 EXCEPT What do we get if we replace UNION by EXCEPT? Find the sids of all sailors who have reserved red boats but not green boats SELECT S.name FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ EXCEPT SELECT S.name FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘green’ Name of sailors who’ve reserved red boats Name of sailors who’ve reserved green boats
20
Database Management Systems, R. Ramakrishnan and J. Gehrke20 Find names of sailors who’ve reserved a red and a green boat
21
Database Management Systems, R. Ramakrishnan and J. Gehrke21 Find names of sailors who’ve reserved a red and a green boat Sailors(sid, sname, rating, age) Reserves(sid, bid, day) Boats(bid, bname, color) bid is a boat sid has a reservation for bid ‘red’ Reserves(sid, bid, day) Boats(bid, bname, color) That bid is a boat sid also has a reservation for another bid ‘green’ B2 R2 B1 R1 SELECT S.name FROM Sailors S, Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE S.sid=R1.sid AND R1.bid=B1.bid The sailor reserves 1 st boat AND S.sid=R2.sid AND R2.bid=B2.bid The same sailor reserves 2 nd boat AND (B1.color=‘red’ AND B2.color=‘green’)
22
Database Management Systems, R. Ramakrishnan and J. Gehrke22 Find names of sailors who’ve reserved a red and a green boat No boat has two colors → Result is empty ! SELECT S.name FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND (B.color=‘red’ AND B.color=‘green’) Can’t we say:
23
Database Management Systems, R. Ramakrishnan and J. Gehrke23 Find names of sailors who’ve reserved a red and a green boat v INTERSECT : Can be used to compute the intersection of any two union-compatible sets of tuples. v Included in the SQL/92 standard, but some systems don’t support it. SELECT S.name FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ INTERSECT SELECT S.name FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘green’ Name of sailors who’ve reserved red boats Name of sailors who’ve reserved green boats
24
Database Management Systems, R. Ramakrishnan and J. Gehrke24 Nested Queries v A very powerful feature of SQL: a WHERE clause can itself contain an SQL query! (Actually, so can FROM and HAVING clauses.) v To understand semantics of nested queries, think of a nested loops evaluation: For each Sailors tuple, check the qualification by computing the subquery. v To find sailors who’ve not reserved #103, use NOT IN. SELECT S.sname FROM Sailors S WHERE S.sid IN ( SELECT R.sid FROM Reserves R WHERE R.bid=103) Find names of sailors who’ve reserved boat #103 All “boat 103” reservations Sailor S has at least one of these reservations
25
Database Management Systems, R. Ramakrishnan and J. Gehrke25 Query : Find names of sailors who’ve reserved boat #103 Nested Queries with Correlation (1) EXISTS tests whether a set is nonempty. SELECT S.sname FROM Sailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE S.sid=R.sid AND R.bid=103) Sailor S reserves boat 103
26
Database Management Systems, R. Ramakrishnan and J. Gehrke26 NOT EXIST SELECT S.sname FROM Sailors S WHERE NOT EXISTS (SELECT * FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid) Use NOT EXIST to find the names of sailors who have not reserved a red boat
27
Database Management Systems, R. Ramakrishnan and J. Gehrke27 Query : Find names of sailors who reserve boat 103 at most once. Nested Queries with Correlation (2) UNIQUE returns true if no row appears more than once. (Note: returns true if answer is empty) Can we replace “SELECT R.bid” by “ SELECT * ” ? No, A sailor may reserve boat 103 on different days; and UNIQUE would return true SELECT S.sname FROM Sailors S WHERE UNIQUE (SELECT R.bid FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid) “at most once”
28
Database Management Systems, R. Ramakrishnan and J. Gehrke28 More on Set-Comparison Operators v Also available: op ANY, op ALL, where op : ˃, ˂, =, ≠, ≥, ≤ v Example: “Find sailors whose rating is greater than that of some sailor called Horatio” SELECT * FROM Sailors S WHERE S.rating > ANY ( SELECT S2.rating FROM Sailors S2 WHERE S2.sname=‘Horatio’) The subquery must return a row that makes the comparison true, in order for S.rating > ANY … to return true
29
Database Management Systems, R. Ramakrishnan and J. Gehrke29 Rewriting INTERSECT Queries Using IN Find sid’s of sailors who’ve reserved both a red and a green boat: SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ ( SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=‘green’) Similarly, we can rewrite EXCEPT queries using NOT IN. sid of sailors who’ve reserved green boats sid of sailors who’ve reserved red boats AND S.sid IN
30
Database Management Systems, R. Ramakrishnan and J. Gehrke30 Division Useful for expressing queries like: Find sailors who have reserved all boats XYY A B X A/B No yellow nor green Division No red nor green
31
Database Management Systems, R. Ramakrishnan and J. Gehrke31 Division Operations in SQL (1) Find names of sailors who’ve reserved all boat: SELECT S.sname FROM Sailors S WHERE NOT EXIST ((SELECT B.bid FROM Boats B) EXCEPT (SELECT R.bid FROM Reserves R WHERE R.sid = S.sid )) All boats All boats reserved by the sailor Boats not reserved by the sailor The sailor reserved all boats
32
Database Management Systems, R. Ramakrishnan and J. Gehrke32 Division Operations in SQL (2) Find names of sailors who’ve reserved all boat: SELECT S.sname FROM Sailors S WHERE NOT EXIST ((SELECT B.bid FROM Boats B WHERE NOT EXISTS (SELECT R.bid FROM Reserves R WHERE R.bid = B.bid AND R.sid = S.sid)) Sailor S such that … there is no boat B without … a Reserves tuple showing S reserved B. Sailor S reserved boat B such that there is no boat B without a reservation Sailor S showing
33
Database Management Systems, R. Ramakrishnan and J. Gehrke33 Aggregate Operators Significant extension of relational algebra COUNT (*)The number of rows in the relation COUNT ([DISTINCT] A) The number of (unique) values in the A column SUM ([DISTINCT] A) The sum of all (unique) values in the A column AVG ([DISTINCT] A) The average of all (unique) values in the A column MAX (A)The maximum value in the A column MIN (A)The minimum value in the A column
34
Database Management Systems, R. Ramakrishnan and J. Gehrke34 Aggregate Operators SELECT AVG (S.age) FROM Sailors S WHERE S.rating=10 SELECT COUNT (*) FROM Sailors S SELECT AVG ( DISTINCT S.age) FROM Sailors S WHERE S.rating=10 SELECT S.sname FROM Sailors S WHERE S.rating= ( SELECT MAX (S2.rating) FROM Sailors S2) SELECT COUNT ( DISTINCT S.rating) FROM Sailors S WHERE S.sname=‘Bob’ Count the number of sailors Find the average age of sailors with a rating of 10 Find the average of the distinct ages of sailors with a rating of 10 Count the number of distinct ratings of sailors called “Bob” Find the name of sailors with the highest rating
35
Database Management Systems, R. Ramakrishnan and J. Gehrke35 Aggregate Operators SELECT AVG (S.age) FROM Sailors S WHERE S.rating=10 SELECT COUNT (*) FROM Sailors S SELECT AVG ( DISTINCT S.age) FROM Sailors S WHERE S.rating=10 SELECT S.sname FROM Sailors S WHERE S.rating= ( SELECT MAX (S2.rating) FROM Sailors S2) SELECT COUNT ( DISTINCT S.rating) FROM Sailors S WHERE S.sname=‘Bob’
36
Database Management Systems, R. Ramakrishnan and J. Gehrke36 SELECT S.sname FROM Sailors S WHERE ( SELECT MAX (S2.rating) FROM Sailors S2 ) = S.rating SELECT S.sname FROM Sailors S WHERE S.rating = (SELECT MAX(S2.rating) FROM Sailors S2) Comparing a number with a relation is allowed here Allowed in SQL/92 standard, but is not supported in some systems Find name and age of the oldest sailor(s)
37
Database Management Systems, R. Ramakrishnan and J. Gehrke37 SELECT S.sname, MAX (S.age) FROM Sailors S Find name and age of the oldest sailor(s) If the SELECT clause uses an aggregate operation, then it must use only aggregate operations unless the query contains a GROUP BY clause (aggregate value for each group – discussed later.) Only aggregate operations allowed Illegal
38
Database Management Systems, R. Ramakrishnan and J. Gehrke38 SIMPLE GROUP BY v So far, we’ve applied aggregate operators to all (qualifying) tuples. Relation QualifierAggregator 32 SELECT AVG (S.age) FROM Sailors S WHERE S.rating=10 Find the average age of sailors with a rating of 10 Qualifier Aggregator
39
Database Management Systems, R. Ramakrishnan and J. Gehrke39 GROUP BY and HAVING v So far, we’ve applied aggregate operators to all (qualifying) tuples. v Sometimes, we want to apply them to each of several groups of tuples. Relation QualifierAggregator 32 Relation Group 1 Aggregator 1212 Group 2 Group 3 Aggregator 9 11
40
Database Management Systems, R. Ramakrishnan and J. Gehrke40 GROUP BY and HAVING (2) Consider: Find the age of the youngest sailor for each rating level. /* Min(age) for multiple groups – If we know that rating values go from 1 to 10, we can write 10 queries that look like this: – In general, we don’t know how many rating levels exist, and what the rating values for these levels are ! SELECT MIN (S.age) FROM Sailors S WHERE S.rating = i For i = 1, 2,..., 10:
41
Database Management Systems, R. Ramakrishnan and J. Gehrke41 Queries With GROUP BY and HAVING SELECT [DISTINCT] target-list FROM relation-list WHERE qualification GROUP BY grouping-list HAVING group-qualification SELECT FROM WHERE GROUP BY HAVING MIN(Attribute) Output a table
42
Database Management Systems, R. Ramakrishnan and J. Gehrke42 Queries With GROUP BY and HAVING The target-list contains: (i) attribute names, (ii) terms with aggregate operations (e.g., MIN (S.age)). Each answer tuple belongs to a group. The attribute list must be a subset of grouping-list. A group is a set of tuples that have the same value for all attributes in grouping-list. SELECT [DISTINCT] target-list FROM relation-list WHERE qualification GROUP BY grouping-list HAVING group-qualification
43
Database Management Systems, R. Ramakrishnan and J. Gehrke43 Conceptual Evaluation 1. The cross-product of relation-list is computed 2. Tuples that fail qualification are discarded 3. `Unnecessary’ fields are deleted 4. The remaining tuples are partitioned into groups by the value of attributes in grouping-list. 5. The group-qualification is then applied to eliminate some groups 6. One answer tuple is generated per qualifying group SELECT [DISTINCT] target-list FROM relation-list WHERE qualification GROUP BY grouping-list HAVING group-qualification
44
Database Management Systems, R. Ramakrishnan and J. Gehrke44 Find the age of the youngest sailor with age ≥ 18, for each rating with at least 2 such sailors SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age >= 18 GROUP BY S.rating HAVING COUNT (*) > 1 Input relation Disqualify Only S.rating and S.age are mentioned in SELECT 4 rating groups age Answer Only one group satisfies HAVING Sailors
45
Database Management Systems, R. Ramakrishnan and J. Gehrke45 Find the age of the youngest sailor with age ≥ 18 SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age >= 18 GROUP BY S.rating HAVING COUNT (*) > 1 Find the age of the youngest sailor with age ≥ 18, for each rating Find the age of the youngest sailor with age ≥ 18, for each rating with at least 2 such sailors SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age >= 18 GROUP BY S.rating SELECT MIN (S.age) FROM Sailors S WHERE S.age >= 18 “ GROUP BY and HAVING” Examples
46
Database Management Systems, R. Ramakrishnan and J. Gehrke46 For each red boat, find the number of reservations for this boat SELECT B.bid, COUNT (*) AS scount FROM Boats B, Reserves R WHERE R.bid=B.bid AND B.color=‘red’ GROUP BY B.bid 1) Find all reservations for red boats 2) Group the reservations for red boats according to bid 3) Count the number of reservations for each red-boat group
47
Database Management Systems, R. Ramakrishnan and J. Gehrke47 Illegal Having Clause SELECT B.bid, COUNT (*) AS scount FROM Boats B, Reserves R WHERE R.bid=B.bid GROUP BY B.bid HAVING B.color=‘red’ B.Color is not in the grouping-list Note: HAVING clause is to select groups ! HAVING B.color=‘red’ SELECT FROM WHERE GROUP BY “bid” GROUP BY “bid” HAVING “red” ? Output a table Number of reservation for each boat
48
Database Management Systems, R. Ramakrishnan and J. Gehrke48 Find the age of the youngest sailor older than 18, for each rating with at least 2 sailors Step 1: Select the desired tuples (using WHERE) Step 2: Form the groups (using GROUP BY) Step 3: Select the desired groups (using HAVING) Step 4: Compute the aggregation for each group (using COUNT, MAX, AVG, etc.) Needs aggregate function
49
Database Management Systems, R. Ramakrishnan and J. Gehrke49 Find the age of the youngest sailor older than 18, for each rating with at least 2 sailors Sailors Age >18 Group S.rating Rating Size>1 Min. age 22 26 WHERE S.age > 18 GROUP BY S.rating HAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating) 14 3 2 MIN(S.age)
50
Database Management Systems, R. Ramakrishnan and J. Gehrke50 Find the age of the youngest sailor older than 18, for each rating with at least 2 sailors WHERE S.age > 18 GROUP BY S.rating HAVING 1 ˂ (SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating) 14 3 2 SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING 1 ˂ ( SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating) MIN(S.age) 1 1 2 2 3 3 4 4
51
Database Management Systems, R. Ramakrishnan and J. Gehrke51 SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING 1 ˂ ( SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating) Find the age of the youngest sailor older than 18, for each rating with at least 2 sailors 1) Find all sailors older than 18 2) Group qualified sailors according to rating 3.2) Discard groups with less than two sailors 4) Find youngest age for each qualified group 3.1) Count the number of sailors in a group Number of sailors with this rating
52
Database Management Systems, R. Ramakrishnan and J. Gehrke52 Find the age of the youngest sailor older than 18 for each rating that has at least 2 sailors SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING 1 ˂ ( SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating) What if HAVING clause is replaced by “HAVING COUNT(*) > 1” ? What if HAVING clause is replaced by “HAVING COUNT(*) > 1” ? Find the age of the youngest sailor older than 18, for each rating level that has at least two such sailors (MORE IN NEXT PAGE)
53
Database Management Systems, R. Ramakrishnan and J. Gehrke53 Find the age of the youngest sailor older than 18 for each rating that has at least 2 sailors SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING 1 ˂ ( SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating) Counting includes sailors younger than 18 At least 2 sailors SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING COUNT (*) › 1 Counting only adult sailors At least 2 such sailors, i.e., older than 18 “age” is not mentioned in this subquery Find the age of the youngest sailor older than 18 for each rating level that has at least two such sailors
54
Database Management Systems, R. Ramakrishnan and J. Gehrke54 Find the age of the youngest sailor older than 18, for each rating that has at least 2 sailors Shows HAVING clause can also contain a subquery. We can use S.rating inside the nested subquery because it has a single value for the current group of sailors. SELECT S.rating, MIN (S.age) FROM Sailors S WHERE S.age > 18 GROUP BY S.rating HAVING 1 ˂ ( SELECT COUNT (*) FROM Sailors S2 WHERE S.rating = S2.rating)
55
Database Management Systems, R. Ramakrishnan and J. Gehrke55 Find those ratings for which the average age is the minimum over all ratings SELECT S.rating FROM Sailors S WHERE S.age = ( SELECT MIN ( AVG (S2.age)) FROM Sailors S2) Aggregate operations cannot be nested
56
Database Management Systems, R. Ramakrishnan and J. Gehrke56 Find those ratings for which the average age is the minimum over all ratings SELECT Temp.rating, Temp.avgage FROM ( SELECT S.rating, AVG (S.age) AS avgage FROM Sailors S GROUP BY S.rating) AS Temp WHERE Temp.avgage = ( SELECT MIN (Temp.avgage) FROM Temp) Correct solution (in SQL/92): Minimum over all ratings Find average age for each rating group Average age for some rating group Temp rating avgage
57
Database Management Systems, R. Ramakrishnan and J. Gehrke57 Null Values v Field values in a tuple are sometimes –unknown (e.g., a rating has not been assigned), or –inapplicable (e.g., no spouse’s name). v SQL provides a special value null for such situations.
58
Database Management Systems, R. Ramakrishnan and J. Gehrke58 Null Values The presence of null complicates many issues: Special operators needed, e.g., IS NULL to test if a value is null. Is rating>8 true or false when rating is equal to null? null What about AND, OR and NOT ? Need a 3-valued logic (true, false, and unknown), e.g., (unknown OR false) = unknown. Meaning of constructs must be defined carefully, e.g., WHERE clause eliminates rows that don’t evaluate to true. Null + 5 = null; but SUM (null, 5) = 5. (nulls can cause some unexpected behavior) New operators (in particular, outer joins) possible/needed.
59
Database Management Systems, R. Ramakrishnan and J. Gehrke59 Outer Joins R1S1 S1 R1 sidsnameratingagebidday 22dustin745.010110/10/96 31lubber855.55null 58rusty1035.010311/12/96 No match in R1
60
Database Management Systems, R. Ramakrishnan and J. Gehrke60 Integrity Constraints (Review) An IC describes conditions that every legal instance of a relation must satisfy. – Inserts/deletes/updates that violate IC’s are disallowed. – Can be used to ensure application semantics (e.g., sid is a key), or prevent inconsistencies (e.g., sname has to be a string, age must be < 200) Types of IC’s: Domain constraints, primary key constraints, foreign key constraints, general constraints. – Domain constraints: Field values must be of right type. Always enforced.
61
Database Management Systems, R. Ramakrishnan and J. Gehrke61 General Constraints Useful when more general ICs than keys are involved. CREATE TABLE Sailors ( sid INTEGER, sname CHAR(10), rating INTEGER, age REAL, PRIMARY KEY (sid), CHECK ( rating >= 1 AND rating <= 10 ) A general constraint
62
Database Management Systems, R. Ramakrishnan and J. Gehrke62 v Constraints can be named v Can use queries to express constraint A named general constraint Find the name of the boat General Constraints CREATE TABLE Reserves ( sname CHAR(10), bid INTEGER, day DATE, PRIMARY KEY (bid,day), CONSTRAINT noInterlakeRes CHECK (`Interlake’ <> ( SELECT B.bname FROM Boats B WHERE B.bid=bid))) For each boat
63
Database Management Systems, R. Ramakrishnan and J. Gehrke63 Constraints Over Multiple Relations CREATE ASSERTION smallClub CHECK ( ( SELECT COUNT (S.sid) FROM Sailors S) + ( SELECT COUNT (B.bid) FROM Boats B) < 100 ) 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 ) Number of boats plus number of sailors is < 100 This is not checked in Boats. If it is not modified, the number of Boats tuples can be anything Awkward and wrong! ASSERTION is the right solution; not associated with either table
64
Database Management Systems, R. Ramakrishnan and J. Gehrke64 Triggers Trigger is a procedure that starts automatically if specified changes occur to the DBMS Three parts Event A change to the database that activates the trigger (e.g., BEFORE insert, AFTER update) Condition A query or test that is run when the trigger is activated (e.g., WHEN total salaries > $1M) Action A procedure that is executed when the trigger is activated and its condition is true Condition Action Event
65
Database Management Systems, R. Ramakrishnan and J. Gehrke65 Specify Action The action can be executed before, after, or instead of the triggering event BEFORE The action is executed before the event that triggered the action AFTER The action is executed after the triggering event INSTEAD OF The action is executed and the triggering event is never executed (1) Event (2) Action trigger
66
Database Management Systems, R. Ramakrishnan and J. Gehrke66 Two kinds of triggers v Statement-level trigger: executed once for all the tuples that are changed in one SQL statement. REFERENCING NEW TABLE AS newtuples, /* Set of new tuples OLD TABLE AS oldtuples /* Set of old tuples v Row-level trigger: executed once for each modified tuple. REFERENCING OLD AS oldtuple, NEW AS newtuple newtuples, oldtuple, newtuple can be used in the CONDITION and ACTION clauses
67
Database Management Systems, R. Ramakrishnan and J. Gehrke67 CountTable agecount 17113 180............ 992 Trigger Examples (SQL:1999) CREATE TRIGGER InitCounter BEFORE INSERT ON SAILORS FOR EACH STATEMENT INSERT INTO CountTable SET count = 0 WHERE age = 18 CREATE TRIGGER IncrCount AFTER INSERT ON SAILORS FOR EACH ROW UPDATE CountTable SET count = count + 1 WHERE age = 18 Statement-level trigger: execute trigger only once to initialize counter Statement-level trigger: execute trigger only once to initialize counter Row-level trigger: evaluate each new sailor to decide whether to increment the counter CountTable agecount 17113 18229............ 992
68
Database Management Systems, R. Ramakrishnan and J. Gehrke68 Statement-Level Trigger Example (SQL:1999) CREATE TRIGGER youngSailorUpdate AFTER INSERT ON SAILORS /* Event REFERENCING NEW TABLE AS NewSailors FOR EACH STATEMENT /* Statement-level trigger (default) INSERT /* Action INTO YoungSailors(sid, name, age, rating) SELECT sid, name, age, rating FROM NewSailors N WHERE N.age <= 18 Give a table name to the set of newly inserted tuples Maintain information on young sailors in a separate YoungSailors table Sailors NewSailors ≤ 18 YoungSailors TRIGGER New tuples Insert
69
Database Management Systems, R. Ramakrishnan and J. Gehrke69 Row-Level Trigger Example (SQL:1999) CREAT TRIGGER RatingTrigger AFTER UPDATE OF rating ON Sailors REFERENCING OLD AS OldTuple, /* value before update NEW AS NewTuple /* value after update WHEN (OldTupple.rating ˃ NewTupple.rating) FOR EACH ROW UPDATE Sailors SET rating = OldTuple.rating WHERE SID = NewTuple.SID /* Condition /* Event /* Row-level trigger /* Action: Restore /* any attempt to /* lower rating Sailors(SID, sname, rating, age)
70
Database Management Systems, R. Ramakrishnan and J. Gehrke70 Summary v SQL was an important factor in the early acceptance of the relational model; more natural than earlier, procedural query languages. v Relationally complete; in fact, significantly more expressive power than relational algebra. v Even queries that can be expressed in relational algebra can often be expressed more naturally in SQL. v Many alternative ways to write a query; optimizer should look for most efficient evaluation plan. – In practice, users need to be aware of how queries are optimized and evaluated for best results.
71
Database Management Systems, R. Ramakrishnan and J. Gehrke71 Summary (Contd.) v NULL for unknown-field values brings many complications v SQL allows specification of rich integrity constraints v Triggers respond to changes in the database
72
Database Management Systems, R. Ramakrishnan and J. Gehrke72 Midterm v Closed-book exam v Chapters 1, 2, 3, 5, 8 v Date: March 5, 2015 How to prepare ? –For each chapter, spend two hours to review the slides –Spend three hours to practice the SQL examples in the textbook (Chapter 5) –Practice the homeworks
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.