Hamish Burke | 2025-04-03

Related to: #databases


Relational Algebra

Relation = A set of tuples with the same attributes (rows with the same columns)
Schema = Describes a relations attribute names and types

Operations

Selection

σ{cond}(R)σ{GPA=3.5}(Student)

Ricks rows in R that satisfy cond

Projection

π{attrs}(R)π{Lname,Fname}(Student)

Picks columns attrs from R (and drops duplicates)

Rename

ρ{new(old)}(R)ρ{S(Students)}(Student)

Change relation or attribute names


Questions

  1. 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))
  1. Rename employee to E and attributes EmpID -> ID, Salary -> Sal
ρ{E(Employee)}(Employee)
ρ{ID(EmpID)}(E)
ρ{Sal(Salary)}(E)

-- or

ρ{E(ID, Name, Dept, Sal)}(Employee)
  1. Relation A(X, Y) and B(X, Y) share schema. Write RA to find tuples in A but not in B
π{X,Y}(A) - π{X,Y}(B)

-- As they share a schema, don't need to project

A - B
  1. Given R(A,B) and S(C), show the RA for pairing every R row with every S row
π{A,B}(R) X π{C}(S)

-- No need to project (as using all attributes in both)

R x S
  1. Relations Orders(OID, CustID, Total) and Customer(CustID, Name). Get OID,Name,Total for orders over $100
π{OID, Name, Total}(Customer ⋈{Total > 100} Orders)
  1. Relations R(A,B,C) and S(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)
  1. Enrolled(StudentID, CourseID) and Required(CourseID). Find students who've taken all required courses. Express in RA using division
π{StudentID, CourseID}(Enrolled) % π{CourseID}(Required)
  1. Translate sql to RA
SELECT DiSTINCT Dept
FROM Employee
WHERE Salary BETWEEN 50000 AND 80000;

??