Hamish Burke | 2025-04-03
Related to: #databases
Relational Algebra
- Query language
- Introduced by Codd (1970)
Relation = A set of tuples with the same attributes (rows with the same columns)
Schema = Describes a relations attribute names and types
Operations
Selection
Ricks rows in cond
Projection
Picks columns attrs from
Rename
Change relation or attribute names
Questions
- Given Relation
Employee(EmpID, Name, Dept, Salary), write relational-algebra to get Name and Salary of employees in the "Sales" department
π{Name, Salary}(σ{Dept = 'Sales'}(Employee))
- Rename employee to
Eand attributesEmpID -> ID,Salary -> Sal
ρ{E(Employee)}(Employee)
ρ{ID(EmpID)}(E)
ρ{Sal(Salary)}(E)
-- or
ρ{E(ID, Name, Dept, Sal)}(Employee)
- Relation
A(X, Y)andB(X, Y)share schema. Write RA to find tuples inAbut not inB
π{X,Y}(A) - π{X,Y}(B)
-- As they share a schema, don't need to project
A - B
- Given
R(A,B)andS(C), show the RA for pairing everyRrow with everySrow
π{A,B}(R) X π{C}(S)
-- No need to project (as using all attributes in both)
R x S
- Relations
Orders(OID, CustID, Total)andCustomer(CustID, Name). GetOID,Name,Totalfor orders over $100
π{OID, Name, Total}(Customer ⋈{Total > 100} Orders)
- Relations
R(A,B,C)andS(B,D). Write RA using natural join. Then rewrite as a theta-join + projection
-- natural join
R ⋈ S
-- theta join
π{B}(R ⋈{R.B = S.B} S)
Enrolled(StudentID, CourseID)andRequired(CourseID). Find students who've taken all required courses. Express in RA using division
π{StudentID, CourseID}(Enrolled) % π{CourseID}(Required)
- Translate sql to RA
SELECT DiSTINCT Dept
FROM Employee
WHERE Salary BETWEEN 50000 AND 80000;
??