Sub topic 7
Division and “For All” Queries
Prerequisites and the central idea
Assume you know sets, Cartesian products, relations, and the logic symbols “there exists” and “for all.” This chapter focuses on queries with a universal condition:
> Find students enrolled in every course.
A normal selection checks one tuple. Division checks whether an entity is related to all tuples in another relation.
Relational algebra division
Suppose:
Enrolled(sid, cid)records student-course pairs.Course(cid)lists all courses.
The expression below returns student IDs enrolled in every course:
π_sid,cid(Enrolled) ÷ π_cid(Course)For a relation R(A, B) and a relation S(B), division returns each A value that appears with every B value in S.
The formal definition is:
R ÷ S = π_A(R) − π_A((π_A(R) × S) − R)The expression finds all possible student-course pairs, removes the pairs that actually exist, and identifies students with at least one missing pair. Subtracting those students leaves students with no missing course.
| Student | Enrolled courses | Enrolled in every course? |
|---|---|---|
| 1 | 10, 20 | Yes |
| 2 | 10 | No |
The divisor must contain the attributes being checked, here cid. The remaining attributes, here sid, form the result.
SQL translation with double `NOT EXISTS`
SQL has no standard division operator. The usual translation is:
CREATE TABLE Student (
sid INTEGER PRIMARY KEY,
sname VARCHAR(50)
);
CREATE TABLE Course (
cid INTEGER PRIMARY KEY
);
CREATE TABLE Enrolled (
sid INTEGER,
cid INTEGER,
PRIMARY KEY (sid, cid),
FOREIGN KEY (sid) REFERENCES Student(sid),
FOREIGN KEY (cid) REFERENCES Course(cid)
);
SELECT s.sid
FROM Student AS s
WHERE NOT EXISTS (
SELECT 1
FROM Course AS c
WHERE NOT EXISTS (
SELECT 1
FROM Enrolled AS e
WHERE e.sid = s.sid
AND e.cid = c.cid
)
);Read the query from the inside outward:
- The inner query checks whether a particular student is enrolled in a particular course.
- The first
NOT EXISTSfinds a course for which enrollment is missing. - The outer
NOT EXISTSkeeps the student only when no such course exists.
This implements the logical pattern:
For every course c, the student is enrolled in cwhich is equivalent to:
There does not exist a course c for which the student is not enrolled in cTuple calculus form
A tuple relational calculus expression can state the same condition directly:
{ s |
s ∈ Student ∧
∀c (c ∈ Course →
∃e (e ∈ Enrolled ∧ e.sid = s.sid ∧ e.cid = c.cid))
}The universal variable c ranges over courses. For each course, an enrollment tuple must exist.
Exercise
What does Enrolled ÷ Required(cid) return when Required lists the courses that must be completed?
Show answer
It returns the student IDs that have an enrollment tuple for every course in Required.