03-Relational Algebra - Additional Operators
03-Relational Algebra - Additional Operators
1 2011 - 2012
Relational algebra
2
Operation
Basic operations:
•Selection
•Projection
•Cross Product
•Union
•Different
•Rename
Additional operations:
•Intersection
•Join
•Division
Sam Sambath
R(FirstName, LastName) ⟵ 𝜋𝐹𝑁𝑎𝑚𝑒,𝐿𝑁𝑎𝑚𝑒 (TEMP)
Sok Piseth
8. Assignment Operator
6
T1 ⟵ 𝜎𝑀𝑎𝑗𝑜𝑟="𝐶𝑆" 𝑆𝑇𝑈𝐷𝐸𝑁𝑇𝑆
𝑇2 ⟵ 𝜎𝑇1.𝑆𝑡𝐼𝑑=𝑏𝑜𝑟𝑟𝑜𝑤𝑠.𝑆𝑡𝐼𝑑 (𝑇1 × 𝑏𝑜𝑟𝑟𝑜𝑤𝑠)
Result ⟵ 𝜋𝑆𝑡𝑁𝑎𝑚𝑒 𝑇2
1. Set-Intersection
7
FN LN FN LN FN LN
R S R∩S
2. Join Operation
8
Binary operator.
Syntax: R ⋈<𝑗𝑜𝑖𝑛 𝑐𝑜𝑛𝑑𝑖𝑡𝑖𝑜𝑛> S
Combines related tuples from 2 relations into a single relation.
Like Cartesian Product, combine tuples from 2 relations into single
“longer” tuples, but only those that satisfy matching condition .
Derivation: R ⋈<𝑗𝑜𝑖𝑛 𝑐𝑜𝑛𝑑𝑖𝑡𝑖𝑜𝑛> S = 𝜎<𝑗𝑜𝑖𝑛 𝑐𝑜𝑛𝑑𝑖𝑡𝑖𝑜𝑛> (𝑅 × 𝑆)
R(a1,
a2, a3); S(b1, b2, b3)
R ⋈<𝑗𝑜𝑖𝑛 𝑐𝑜𝑛𝑑𝑖𝑡𝑖𝑜𝑛> S = T (a1, a2, a3, b1, b2, b3)
Ex: Department ⋈𝑀𝑔𝑟_𝐼𝐷=𝐸𝐼𝐷 Employee
2. Join Operation
9
20 25 50 80 40 35
80 40 35
R ⋈𝐵>𝐶 S
Practice
11
2. 𝑟 ⋈𝐶=𝑆𝐶 𝜌𝑆 𝑆𝐶,𝐷 s
Natural join
16
Proj_Dept
Result of the Natural join: PID PName DNum DName Mgr_ID
102 ProjectY 2 GCA 2
Practice
21
3. 𝑟 ⋈ 𝑠
Practice: Write RA Expression
23
1. List all students’ name and the name of the course they enroll in.
Course Student
CID Cname StudentID Sname
3 Yi Sophea
StudentCourse
#StudentID #CID
1 C1
1 C2
2 C2
2 C1
3 C2
Practice: Write RA Expression
Who has taken a course taught by Anderson? Find their name, course
number, semester and year.
3. Division
28
Syntax: 𝑅 ÷ 𝑆
Precondition: attributes in S must be subset of attributes in R, 𝑆 ⊆ 𝑅 .
Let 𝑟, 𝑠 be relations on schemas R and S, respectively where
R( A1, … Am , B1 , … Bn)
S( B1 , … Bn)
The result of 𝑟 ÷ 𝑠 is a relation on schema R – S = (A1, … Am)
Suited for queries that includes the phrase “for all”.
The result of the division operator 𝑟 ÷ 𝑠 consists of the set of tuples
from 𝑟 defined over the attributes R-S that match the combination of
every tuples in 𝑠 .
3. Division
29
Syntax: 𝑅 ÷ 𝑆 or 𝑅 ∕ 𝑆
Suited for queries that includes the phrase “for all”.
The result of the division operator 𝑟 ÷ 𝑠 consists of the set of tuples
from 𝑟 defined over the attributes R-S that match the combination of
every tuples in 𝑠 .
Precondition: attributes in S must be subset of attributes in R, 𝑆 ⊆ 𝑅 .
Let 𝑟, 𝑠 be relations on schemas R and S, respectively where
R( A1, … Am , B1 , … Bn);
S( B1 , … Bn)
The result of 𝑟 ÷ 𝑠 is a relation on schema R – S = (A1, … Am)
3. Division
30
Ex1:
3. Division
31
Division: 𝑅÷𝑆
= 𝜋𝑦 𝑅 − 𝜋𝑦 ((𝜋𝑦 (𝑅) × 𝑆) − 𝑅)
Where R(x, y) and S(y), y are attributes in 𝑅 and not is 𝑆.
T1 ⟵ 𝜋𝑦 R
T2 ⟵ 𝜋𝑦 ( T1 × S − R)
Result ⟵ T1 − T2
3. Division
32
1001 1 1 1002
1002 1 2
1002 2
1003 2
EID 1003 1
EID PID
T1 ⟵ 𝜋𝑦 R 1003 2
1001 2 1001
1002
Result ⟵ T1 − T2
3. Division
34
1 C1 C1 Math
1 C2 C2 Physic
2 C2
2 C1
3 C2
StudentID
2
3. Division
35