Join and Union Queries
Join and Union Queries
JOIN Queries
SELECT S.sname
FROM Tables to be joined
Sailors S1, Reserves R1
WHERE S1.sid=R1.sid AND R1.bid=103 Join condition (s)
JOIN
Filtering joined tuples not
matching conditions
Example of Conceptual
Evaluation
SELECT S.sname
FROM Sailors S1, Reserves R1
WHERE S1.sid=R1.sid AND R1.bid=103
SELECT S.sname
FROM Sailors S, Reserves R
WHERE S.sid=R.sid AND R.bid=103 It is good style,
sname
however, to use
OR
range variables
SELECT
Sailors, Reserves
always!
FROM
WHERE Sailors.sid=Reserves.sid AND
Reserves.bid=103
Find sailors who’ve reserved at least
one boat
Sailors Reserves Boats
sid sname rating age bid bname color
sid bid day
22 dustin 7 45.0 101 Interlake blue
22 101 10/10/96
31 lubber 8 55.5 102 Interlake red
58 103 11/12/96
58 rusty 10 35.0 103 Clipper green
104 Marine red
SELECT S.sname
Sailors S, Reserves R
SELECT S.sname
FROM
S.sid=R.sid AND bid=103
Sailors S, Reserves R, Boats B
WHERE
FROM
WHERE S.sid=R.sid AND R.bid=B.bid
AND B.color = ‘blue’
Find sids, names of sailors who’ve reserved
a red or a green boat
Boats B1 Reserves R1
bid bname color sid bid day
101 Interlak blue
e 22 101 10/10/96
102 Interlak red 58 103 11/12/96
e
103 Clipper green
Sailors S1
104 Marine red Which relations will
sid sname rating age
we need?
22 dustin 7 45.0
31 lubber 8 55.5 All three!!
58 rusty 10 35.0
Find sid’s and names of sailors who’ve reserved a red or a
green boat(1): Logical OR
Outcome?
1 tuple, 10 columns
Final Result?
1 tuple, 2 columns
Find sid’s and names of sailors who’ve reserved a red or a
green boat (2) : Set UNION
SELECTS.sid, S.sname
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid AND
Sailors that have reserved red boats
B.color=‘red’
UNION
SELECTS.sid, S.sname
FROM Sailors S, Boats B, Reserves R
Sailors that have reserved green boa
bcolor (sid) bid sid sname rating age (sid) bid bcolor
Employee Dept
Name EmpId DeptName Manager
Harry 3415 Finance NULL
Sally 2241 Sales Harriet
George 3401 Finance NULL FOJ : LOJ plus ROJ
Harriet 2202 Sales Harriet
Tim 1123 Executive NULL
NULL NULL Production Charles
Full Outer Join
Find names of Sailors that have not
reserved any boats
• How?
More on Outer Joins
• More complex conditions based on NULL values