SQL: The Query Language (Part II)
SQL: The Query Language (Part II)
SELECT S.sid
UNION: Can be used to FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid
compute the union of any
AND (B.color=‘red’ OR B.color=‘green’)
two union-compatible sets
of tuples (which are
themselves the result of SELECT S.sid
FROM Sailors S, Boats B, Reserves R
SQL queries).
WHERE S.sid=R.sid AND
Also available: EXCEPT R.bid=B.bid
(What do we get if we AND B.color=‘red’
replace UNION by EXCEPT?) UNION
SELECT S.sid
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND
R.bid=B.bid
AND B.color=‘green’
Find sid’s of sailors who’ve reserved a red and a green boat
SELECT S.sid
FROM Sailors S, Boats B1, Reserves R1,
INTERSECT: Can be used to Boats B2, Reserves R2
compute the intersection WHERE S.sid=R1.sid AND R1.bid=B1.bid
AND S.sid=R2.sid AND R2.bid=B2.bid
of any two union-
AND (B1.color=‘red’ AND B2.color=‘green’)
compatible sets of tuples.
Key field!
Included in the SQL/92
SELECT S.sid
standard, but some FROM Sailors S, Boats B, Reserves R
systems don’t support it. WHERE S.sid=R.sid AND
Contrast symmetry of the R.bid=B.bid
AND B.color=‘red’
UNION and INTERSECT INTERSECT
queries with how much SELECT S.sid
the other versions differ. FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND
R.bid=B.bid
AND B.color=‘green’
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 a nested loops
evaluation: For each Sailors tuple, check the qualification by computing
the subquery.
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)