Relational Expression exercises
Relational Expression exercises
A B
0 1
R(A, B):
2 3 1. GammaAvg(A) (R) = {1}
0 1 2. GammaA,B (R) = {(0,1), (2,3), (2,4), (null,4)}
2 4 3. Count(*)=6 //the toal # of tuples in R
null 4 4. Count (A) =4 // the total # of non-null values in A
null 4
B C 5. GammaA (R) = {0, 2, null}
0 1 S(B , C):
2 4
1. GammaB (S) = {(0), (2), (3)}
2 5
2. GammaC, Avg(B) (S) ={(1, 0), (2,0), (4, 2.67), (5,2) }
3 4
0 2
3 4
Database Schema:
Sailors(sid, sname)
Boats(bid, color)
Reserves(sid, bid, date)
1
Find names of sailors who’ve reserved boat
#103
Solution 1: πsname((σbid=103(Reserves) ⋈ Sailors)
Problem? What if two sailors have the same
name? We want to print out the name of a
qualified sailor exactly once, but SET projection
will eliminate ‘duplicate’ sailor names.
Solution 2: πsid, sname(σbid=103(Reserves ⋈ Sailors))
2
Find sailors who’ve ever reserved a red or a
green boat
Can identify all red or green boats, then find sailors
wh’ve reserved one of these boats:
ρ(Tempboats, (σcolor=‘red’ or color=‘green’(Boats))
πsid, sname(πsid(Tempboats ⋈ Reserves) ⋈ Sailors)
Can also define Tempboats using union
Tempboats= σcolor=‘red’(Boats) U
σcolor=‘green’(Boats)
What happens if union is replaced by intersection in
this query? (Tempboat will be empty)
3
Summary
The relational model has rigorously defined
query languages that are simple and powerful.
Relational algebra is more operational; useful
as internal representation for query evaluation
plans.
Several ways of expressing a given query; a
query optimizer should choose the most(?)
efficient version.