Lecture 03
Lecture 03
CS430/630
Lecture 3
Slides based on “Database Management Systems” 3rd ed, Ramakrishnan and Gehrke
Relational Algebra
� Basic operations:
� Selection Selects a subset of rows from relation
� Projection Deletes unwanted columns from relation
� Cross-product Allows us to combine several relations
� Join ⊳⊲ Combines several relations using conditions
� Division A bit more complex, will cover later on
� Set-difference
Union ∪ Intersection ∩
� Renaming Helper operator, does not derive new result, just
renames relations and fields
(R(F ), E)
� F contains oldname newname pairs
Operator Precedence
(( Sailors)
snam rating 8
sname
Sailors
rating 8
Join Reserves ⊳⊲ Sailors
Reserves Sailors
sid bid day sid sname rating age
22 101 10/10/96 22 dustin 7 45.0
58 103 11/12/96 31 lubber 8 55.5
Reserves ⊳⊲ Sailors
58 rusty 10 35.0
sid bid day sname rating age
22 101 10/10/9 dustin 7 45.0
6
58 103 11/12/9 rusty 10 35.0
6
color 'red'
empty!
Sample Query 3
Sailors Boats
sid sname rating age bid name color
Reserves
sid bid day
(TempJoin(1 f f f f 4),
1,2 2,3 3,4
S1⊳⊲ S1.age S2.age S2)
(LeftHalf , f f f4
TempJoin)
f 1,
2, 3,
� Old solution:
sname(( Boats) ⊳⊲ Reserves ⊳⊲ Sailors)
color ' red
'
� Returns an empty relation!
� It’s looking for matches on name as well as bid, sid
Sample Query 2 on modified schema
Sailors Boats
Reserves bid name color
sid name rating age
sid bid day
'
� Here we can project out boat names before join to Sailors
name((( B)⊳ R)⊳⊲ S)
⊲
bid color 'red'
sid sname rating age
Another self join: 28 yuppy 9 35.0
Close competitors
31 lubber 8 55.5
44 guppy 5 35.0
58 rusty 10 35.0
� Find pairs of sailors (sids) with ratings that differ by no more
than one.
sid1 sid2
(S1,Sailors) (S2,Sailors)
28 28
(TempJoin(1sid1,5sid2), 28 31
S1⊳ S1.ratingS 2.rating 1^S1.rating S 2.rating 1 28 58
⊲ S2) TempJoin 31 28
… …
sid1,sid2
� We don’t want a lot of these results…
sid sname rating age
Another self join 28 yuppy 9 35.0
31 lubber 8 55.5
44 guppy 5 35.0
58 rusty 10 35.0
� Find pairs of different sailors (sids) with ratings that differ
by no more than one, listing each unordered pair once.
(S1,Sailors) (S2,Sailors)
(TempJoin(1 sid1,5 sid2),
S1⊳ S1.rating S2.rating 1^ S1.rating S2.rating 1^ S1.sid
S2)
⊲ S2.sid