Presentation is loading. Please wait.

Presentation is loading. Please wait.

Basic SQL Lecture 6 Fall 2008 1.

Similar presentations


Presentation on theme: "Basic SQL Lecture 6 Fall 2008 1."— Presentation transcript:

1 Basic SQL Lecture 6 Fall 2008 1

2 Queries non expressible in Relational Algebra
Find the average rating of sailors older than 30 Find the number of boats On Sailors, for each rating, find the average age We cannot express recursive closure queries 

3 More .. (S’(superiorSid sid),  superiorSid (sid=99 (Sailors)))
Consider : Sailors (sid:integer,sname:string(20),rating:integer,age:float,superiorSid:integer) We cannot express recursive closure queries like Find all superiors of a sailor whose sid is 99. (S’(superiorSid sid),  superiorSid (sid=99 (Sailors))) (S’’(superiorSid sid),  superiorSid ((S’ Sailors))) (S’’’(superiorSid sid),  superiorSid ((S’’ Sailors))) S’  S’’  S’’’ …. We cannot express these kinds of queries without a looping mechanism.

4 R1 Example Instances We will use these instances of the Sailors and Reserves relations in our examples. If the key for the Reserves relation contained only the attributes sid and bid, how would the semantics differ? S1 S2

5 Basic SQL Query SELECT target-list FROM relation-list WHERE qualification relation-list A list of relation names (possibly with a range-variable after each name). One name can appear more than once, with different range-variable names. target-list A list of attributes of the relations in relation-list

6 Basic SQL Query SELECT target-list FROM relation-list WHERE qualification qualification Comparisons (“Attr op const” or “Attr1 op Attr2”, where op is one of =, >, >=, <, <=, <>) combined using AND, OR and NOT.

7 Basic SQL Query: Examples
SELECT S.sname FROM Sailors S WHERE S.age > 50 SELECT DISTINCT S.sname FROM Sailors S WHERE S.age > 50

8 Basic SQL Query SELECT [DISTINCT] target-list FROM relation-list
WHERE qualification DISTINCT is an optional keyword indicating that the answer should not contain duplicates. Default is that duplicates are not eliminated!

9 Set vs. Bag (Multiset) Set: {1, 2, 3} Bag: {1, 2, 2, 2, 3, 3}
No duplicates, no order Bag: {1, 2, 2, 2, 3, 3} Duplicate possible, no order Membership test Same SQL uses “Bag Semantics” Relational algebra uses “Set Semantics”

10 Basic SQL Query: Some Examples
SELECT * FROM Sailors SELECT * FROM Sailors WHERE age > 50 SELECT sid FROM Sailors WHERE age > 50 SELECT S.sname FROM Sailors AS S WHERE S.age > 50 SELECT S.sname FROM Sailors S WHERE S.age > 50 SELECT DISTINCT S.sname FROM Sailors S WHERE S.age > 50 SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103

11 Conceptual Evaluation Strategy
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. This strategy is probably the least efficient way to compute a query! An optimizer will find more efficient strategies to compute the same answers.

12 Conceptual Evaluation Strategy
Nested loops evaluation: Foreach tuple t1 in R1 Foreach tuple tn in Rn 1. Substitute the attribute names in the qualification part with values from t1, …, tn 2. If the modified qualification part evaluates True then output target-attribute-values else do nothing end SELECT target-attribute-list FROM R1, …, Rn WHERE qualification

13 Example: Conceptual Evaluation
SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND R.bid=103

14 A Note on Range Variables
Really needed only if the same relation appears twice in the FROM clause. The previous query can also be written as: SELECT S.sname FROM Sailors S, Reserves R WHERE S.sid=R.sid AND bid=103 It is good style, however, to use range variables always! SELECT sname FROM Sailors, Reserves WHERE Sailors.sid=Reserves.sid AND bid=103 OR

15 Find sailors (sids) who’ve reserved at least one boat
SELECT S.sid FROM Sailors S, Reserves R WHERE S.sid=R.sid Is it different from algebra query below? How many times the same sid may appear? What is the effect of replacing S.sid by S.sname in the SELECT clause?

16 Expressions and Strings
SELECT S.age, age1=S.age-5, 2*S.age AS age2 FROM Sailors S WHERE S.sname LIKE ‘B_%B’ Illustrates use of arithmetic expressions and string pattern matching: Find triples (of ages of sailors and two fields defined by expressions) for sailors whose names begin 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 any one character and `%’ stands for 0 or more arbitrary characters.

17 Strings: LIKE and NOT LIKE
LIKE (NOT LIKE) is used for string matching. SELECT S.sname, S.age FROM Sailors S WHERE S.sname LIKE ‘B%’ SELECT S.sname, S.age FROM Sailors S WHERE S.sname NOT LIKE ‘_B%’ SELECT S.sname, S.age FROM Sailors S WHERE S.sname LIKE ‘_B%’

18 Set Operations (back to set semantics)
Select … From … Where… Set-op Where … Set-ops: All duplicates removed! Union Intersect Except (difference) Bag version Union all, Intersect all, Except all

19 Find sid’s of sailors who’ve reserved a red or a green boat
UNION: Can be used to compute the union of any two union-compatible sets of tuples (which are themselves the result of SQL queries). If we replace OR by AND in the first version, what do we get? Also available: EXCEPT (What do we get if we replace UNION by EXCEPT?) SELECT S.sid 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’) SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ UNION AND B.color=‘green’

20 Find sid’s of sailors who’ve reserved a red and a green boat
SELECT S.sid FROM Sailors S, Boats B1, Reserves R1, Boats B2, Reserves R2 WHERE S.sid=R1.sid AND R1.bid=B1.bid AND S.sid=R2.sid AND R2.bid=B2.bid AND (B1.color=‘red’ AND B2.color=‘green’) INTERSECT: Can be used to compute the intersection of any two union-compatible sets of tuples. Included in the SQL/92 standard, but some systems don’t support it. Contrast symmetry of the UNION and INTERSECT queries with how much the other versions differ. SELECT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ INTERSECT AND B.color=‘green’

21 Except EXCEPT: Can be used to compute the set-difference of any two union-compatible sets of tuples (which are themselves the result of SQL queries). Find sids of sailors whose rating is 10, but have not reserved boat #103 SELECT S.sid FROM Sailors S WHERE S.rating = 10 EXCEPT SELECT R.sid FROM Reserves R WHERE R.bid=103

22 Qualification involving Sets
Value IN SET Value NOT IN SET EXISTS SET NOT EXISTS SET UNIQUE SET Value op ANY SET Value op ALL SET op is one of =, >, >=, <, <=, <> Where do we get SET from? Select statement! Nested queries.

23 Nested Queries Find names of sailors who’ve reserved boat #103:
SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) A very powerful feature of SQL: a WHERE clause can itself contain an SQL query! (Actually, so can FROM and HAVING clauses.) To find sailors who’ve not reserved #103, use NOT IN. To understand semantics of nested queries, think of nested loops evaluation: For each Sailors tuple, check the qualification by computing the subquery.

24 22 IN FALSE This tuple is not selected 58 TRUE: This tuple is selected
Instance of Sailors Instance of Reserves 31 22 IN FALSE This tuple is not selected 58 TRUE: This tuple is selected Answer SELECT S.sname FROM Sailors S WHERE S.sid IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) (SELECT R.sid FROM Reserves R WHERE R.bid=103)

25 Nested Queries with Correlation
Find names of sailors who’ve reserved boat #103: SELECT S.sname FROM Sailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid) EXISTS is another set comparison operator, like IN. Illustrates why, in general, subquery must be re-computed for each Sailors tuple.

26 EXISTS : TRUE : Tuple selected FROM Reserves R
Instance of Sailors Instance of Reserves 31 (SELECT * FROM Reserves R WHERE R.bid=103 AND =R.sid) 58 EXISTS : TRUE : Tuple selected Answer SELECT S.sname FROM Sailors S WHERE EXISTS (SELECT * FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid) EXISTS : FALSE: tuple no selected

27 Nested Queries with Correlation
UNIQUE SET: TRUE : No duplicates tuples in the subquery or empty FALSE: Otherwise Find names of sailors who’ve reserved boat #103 at most once: SELECT S.sname FROM Sailors S WHERE UNIQUE (SELECT R.bid FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid) Why do we have to use R.bid instead of * ?

28 More on Set-Comparison Operators
Can also use NOT IN, NOT EXISTS and NOT UNIQUE: SELECT S.sname FROM Sailors S WHERE S.sid NOT IN (SELECT R.sid FROM Reserves R WHERE R.bid=103) WHERE NOT EXISTS (SELECT * WHERE R.bid=103 AND S.sid=R.sid) Find names of sailors who have not reserved boat #103 SELECT S.sname FROM Sailors S WHERE NOT UNIQUE (SELECT R.bid FROM Reserves R WHERE R.bid=103 AND S.sid=R.sid) Find sailors who have reserved boat #103 more than once

29 More on Set-Comparison Operators
Also available: op ANY, op ALL, op is: op ANY : v op ANY (subquery) : TRUE if the value “v is op” with respect to some value retrieved by the subquery. v: attribute name or a constant

30 More on Set-Comparison Operators: “ANY”
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’)

31 More on Set-Comparison Operators
op ALL: v op ALL (subquery) : TRUE if “v is op” with respect to all the values retrieved by the subquery. Find sailors whose rating is higher than all sailors called Horatio SELECT * FROM Sailors S WHERE S.rating > ALL (SELECT S2.rating FROM Sailors S2 WHERE S2.sname=‘Horatio’) Find sailors with highest rating SELECT * FROM Sailors S WHERE S.rating >= ALL (SELECT S2.rating FROM Sailors S2)

32 More Complex Nested Queries
Find sailors who’ve have reserved a red boat SELECT * FROM Sailors S WHERE EXISTS (SELECT * FROM RESERVES R WHERE S.sid=R.sid AND EXISTS (SELECT * FROM BOATS B WHERE B.COLOR = ‘red’ AND B.bid = R.bid))

33 Rewriting INTERSECT Queries Using Nested Queries
Find sid’s of sailors who’ve reserved both a red and a green boat: SELECT DISTINCT S.sid FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ AND S.sid IN (SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=‘green’)

34 Rewriting INTERSECT Queries Using Nested Queries
To find names of Sailors who’ve reserved both red and green boats, just replace S.sid by S.sname in SELECT clause. (What about INTERSECT query?) SELECT DISTINCT S.sname FROM Sailors S, Boats B, Reserves R WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’ AND EXISTS (SELECT S2.sid FROM Sailors S2, Boats B2, Reserves R2 WHERE S.sid = S2.sid AND S2.sid=R2.sid AND R2.bid=B2.bid AND B2.color=‘green’) Similarly, EXCEPT queries re-written using NOT IN/NOT EXISTS.

35 Division in SQL Find sailors who’ve reserved all boats.
SELECT S.sname FROM Sailors S WHERE NOT EXISTS ((SELECT B.bid FROM Boats B) EXCEPT (SELECT R.bid FROM Reserves R WHERE R.sid=S.sid)) For each sailor S Subquery computes those boats that have not been reserved by the sailor S If the sailor S have reserved all boats, the result of the subquery is empty : NOT EXISTS :TRUE

36 Division in SQL Find sailors who’ve reserved all boats.
Let’s do it the hard way, without EXCEPT: Sailors S such that ... there is no boat B without ... a Reserves tuple showing S reserved B SELECT S.sname FROM Sailors S WHERE NOT EXISTS (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))

37 Conclusions for now This is the “core” part of SQL Bag, nested loop
Similar to Relational Algebra, but not quite A lot of extensions coming up!


Download ppt "Basic SQL Lecture 6 Fall 2008 1."

Similar presentations


Ads by Google