5 RA and Datalog Post 3
5 RA and Datalog Post 3
1. Recap
2. Division
• Assignment ()
RA?
Indy π starID((σ Title = “Indiana Jones and …” Movie) ⋈ StarsIn)
StarWars π starID((σ Title = “Star Wars” Movie) ⋈ StarsIn)
CoolPeopleIndy ∩ StarWars
π name(CoolPeople ⋈ MovieStar)
Find the names of actors who have been in a movie with the same title as
the actor’s name. Which of the following is the correct option?
A. πName((Movie⋈ StarsIn) ⋈ title = name ^ StarID = MovieStar.StarID MovieStar)
B. πName(MovieStar⋈ Name = title ^ MovieStar.StarID = StarID (StarsIn⋈ Movie))
C. πName((StarsIn⋈ (π StarID,NameMovieStar)) ⋈MovieID = Movie.MovieID ^ title =
name Movie)
D. All are correct
E. None are correct
Relational Algebra and Datalog 5
Division
• Notation: r / s or rs
• Useful for expressing queries that include a “for all” or
“for every” phrase,
• r s, with attributes A1, …An, is the set of all tuples <a> such that
for every tuple <b> in s, <a,b> is in r
A/B
• Attributes of B must be a subset
of the attributes of A
A/B1?
Relational Algebra and Datalog 9
Examples of Division A/B
A/B
• Attributes of B must be a subset
of the attributes of A
A/B2?
Relational Algebra and Datalog 10
Examples of Division A/B
A/B
• Attributes of B must be a subset
of the attributes of A
A/B3?
Relational Algebra and Datalog 11
Division Clicker Question
Consider the relations
C D E A B ???
R S 1 2
T 2
1 2 1
2 2
2 2 1
3 2
3 2 1
1 1
B. Y(A)πCR 1 2 1
S(B,A)/Y 2 2 2
C. Z(C)πAS 3 2 3
R(E,C)/Z
D. All of the above
E. None of the above Nothing
Relational Algebra and Datalog 13
Division Clicker Question
Answer B exposed
C D E A B ???
R S 1 2
T 2
1 2 1
2 2
2 2 1
3 2
3 2 1
1 1
B. Y(A)πCR 2 1 1
S(B,A)/Y 2 2 2
C. Z(C)πAS 2 3 3
R(E,C)/Z 1 1
B. Y(A)πCR 1 1 1
S(B,A)/Y 1 2 2
C. Z(C)πAS 1 3 3
R(E,C)/Z
D. All of the above
No, its 1 … we want 2
E. None of the above
Numerator:
iid and cid for every order placed by every customer
iid, cid (Ord )
Denominator:
cid of all customers
cid ( Cust )
Result is numerator/denominator
𝜋𝑖𝑖𝑑,𝑐𝑖𝑑 𝑜𝑟𝑑 ÷ 𝜋𝑐𝑖𝑑 (𝐶𝑢𝑠𝑡))
Relational Algebra and Datalog 17
Find the names of actors who have
been in all movies. Try!
RA?
πName(InAll ⋈MovieStar)
RA?
πName(InAll ⋈MovieStar)
items ordered by
every customer
Witness
(that an Item was ordered by
items not ordered by someone someone)
Query : Find the sin and name of persons who bought every product in the
category “electronics”.
RA
Query : Find the sin and name of persons who bought every product in the
category “electronics”.
RA
goodPersons.buyer-sin = Person.sin
Query : Find the sin and name of persons who bought every product in the
category “electronics”.
Datalog
Query : Find the sin and name of persons who bought every product in the
category “electronics”.
RA
Datalog
RA 𝜋𝑝𝑖𝑑,𝑃1.𝑝𝑖𝑑 𝜎𝑝𝑖𝑑<𝑃1.𝑝𝑖𝑑
[𝑃𝑟𝑜𝑑𝑢𝑐𝑡 ⋈𝑐𝑎𝑡𝑒𝑔𝑜𝑟𝑦=𝑃1.𝑐𝑎𝑡𝑒𝑔𝑜𝑟𝑦∧𝑚𝑎𝑘𝑒𝑟𝑖𝑑≠𝑃1.𝑚𝑎𝑘𝑒𝑟𝑖𝑑 𝜌𝑃1 (𝑃𝑟𝑜𝑑𝑢𝑐𝑡)]
RA
Datalog