Sub topic 2
Division and 'for all' queries
This chapter assumes you know set union, intersection, difference and Cartesian product, basic first-order logic ("for all" and "there exists"), and simple SELECT statements.
Division and 'for all' queries
The division operator answers "for all" questions. For R(A, B) ÷ S(B), the result holds each A value that pairs with every B value in S:
R ÷ S = π_A(R) − π_A((π_A(R) × S) − R)Given Enrolled(sid, cid), the expression Enrolled ÷ π_cid(Course) returns the students enrolled in every course.
Grouping and aggregation in relational algebra
Extended relational algebra adds grouping, written as G with aggregate functions such as COUNT, SUM and MAX. It is the algebraic counterpart of the SQL GROUP BY clause, which appears later in this chapter's plan.
Writing queries in relational algebra
Build a query by applying operators in order. This expression returns the names of students older than 20:
π_sname(σ_age > 20(Student))Selection (σ) keeps matching rows, and projection (π) keeps only the named columns.
Tuple relational calculus
Tuple relational calculus describes the result by a property rather than by a sequence of steps. The tuple variable t ranges over result tuples:
{ t | ∃s ∈ Student (s.age > 20 ∧ t.sname = s.sname) }Safe expressions
An expression is safe when every value in its result comes from the active domain, meaning the values present in the database or the query. The expression { t | ¬(t ∈ Student) } is unsafe because it returns infinitely many tuples.
Domain relational calculus
Domain variables range over single attribute values rather than whole tuples:
{ n | ∃s ∃a (Student(s, n, a) ∧ a > 20) }Relational algebra and safe calculus: equal expressive power
Every safe tuple calculus query can be written in relational algebra, and every relational algebra query can be written in safe tuple calculus. The two formalisms express the same set of queries.
SQL basics: SELECT, WHERE, DISTINCT and duplicates
SELECT keeps duplicate rows, which is called bag semantics. DISTINCT removes them, matching the set semantics of relational algebra.
SELECT DISTINCT sname
FROM Student
WHERE age > 20;SQL joins
A LEFT OUTER JOIN keeps every student, filling the enrollment columns with NULL for students who have no enrollments.
SELECT s.sid, s.sname, e.cid
FROM Student s
LEFT OUTER JOIN Enrolled e ON s.sid = e.sid;Exercise
Write the relational algebra expression for students enrolled in every course, given Enrolled(sid, cid) and Course(cid).
Show answer
πsid,cid(Enrolled) ÷ πcid(Course)