Relational Algebra1
Relational Algebra1
Relational algebra: operands are variables that stand for relations and
relations (sets of tuples), and operations include union, intersection,
selection, projection, Cartesian product, etc
– E.g., (π c-ownerChecking-account) ∩ (π s-ownerSavings-account)
What is a query?
A query is applied to relation instances, and the result of
a query is also a relation instance. (view, query)
– Schemas of input and output fixed, but instances not.
1 2
2 3
1 s
r
A B
r s: 1
2
1
3
Union Example
Union Compatibility
Intersection
Set Difference Operation –
Example
• Relations r, s:
A B A B
1 2
2 3
1 s
r
r – s:
A B
1
1
Difference
Another way to show intersection?
Summary so far:
• E1 U E2 : union
• E1 - E2 : difference
• E1 x E2 : cartesian product
c(E1) : select rows, c = condition (book has p for predicate)
• IIs(E1) : project columns : s =selected columns
x(c1,c2) (E1) : rename, x is new name of E , c1 is new name of
1
column
Combining Tuples of Two Relations
1 10 a
10 a
2 20 b
r 10 b
s
r x s:
A B C D E
1 10 a
1 10 a
1 20 b
1 10 b
2 10 a
2 10 a
2 20 b
2 10 b
Cross Product Example
Cross Product
• How to resolve????
Renaming operator:
• E1 E2 : division
• E1 E2 : join, c = match condition
Practice
• Find names of stars who’ve appeared in a 1994
movie
• Information about movie year available in Movies; so
need an extra join:
σyear=1994(πname(Stars ⋈ AppearIn ⋈ Movies))
• Generalized projection
• Outer join
• Aggregate functions
Generalized projection – calculate
fields
Aggregate Operation – Example
• Relation r:
A B C
7
7
3
10
27
Aggregate
• Functions on more than one tuple
• Samples:
– Sum
– Count-distinct
– Max
– Min
– Count
– Avg
Relation borrower
customer_name loan_number
Jones L-170
Smith L-230
Hayes L-155
Outer Join – Example
• Inner Join
loan Borrower
loan Borrower
loan_number branch_name amount customer_name
L-170 Downtown 3000 Jones
L-230 Redwood 4000 Smith
L-260 Perryridge 1700 null
Outer Join – Example
Right Outer Join
loan borrower
loan borrower
loan_number branch_name amount customer_name
L-170 Downtown 3000 Jones
L-230 Redwood 4000 Smith
L-260 Perryridge 1700 null
L-155 null null Hayes
Summary of Operators - Full
• E1 U E2 : union
• E1 - E2 : difference
• E1 x E2 : cartesian product
c(E1) : select rows, c = condition (book has p for predicate)
• IIs(E1) : project columns : s =selected columns separated by commas,
can have calculations included
x(c1,c2) (E1) : rename, x is new name of E1, c1 is new name of column
• E1 E2 : division
• E1 E2 : outer join, c = match condition, keep the side with the arrows
: assignment – give a new name to an expression to make it easy to read
• as : rename a calculated column
attribute1 changes