Sub topic 20
'For all' queries in SQL
This chapter assumes you can read nested SELECT statements with EXISTS and correlated subqueries. It also assumes you know the quantifiers "for all" and "there exists", and the division operator from relational algebra. The goal is to turn "for every X, there is a Y" into SQL that runs.
Why SQL needs a workaround
Relational algebra has a division operator, so π_sid, cid(Enrolled) ÷ π_cid(Course) returns the students paired with every course. SQL has no such operator. It also has no universal quantifier that you can apply to a subquery directly. It has only EXISTS and NOT EXISTS.
Logic gives a way around this. "For all" can be rewritten as "there does not exist a counterexample":
- Calculus form: ∀c (c ∈ Course → ∃e ∈ Enrolled (e.sid = s.sid ∧ e.cid = c.cid))
- Equivalent form: ¬∃c (c ∈ Course ∧ ¬∃e ∈ Enrolled (e.sid = s.sid ∧ e.cid = c.cid))
The second form maps directly onto two nested NOT EXISTS clauses.
The double NOT EXISTS pattern
This query finds students enrolled in every course.
SELECT s.sid
FROM Student s
WHERE NOT EXISTS (
SELECT *
FROM Course c
WHERE NOT EXISTS (
SELECT *
FROM Enrolled e
WHERE e.sid = s.sid AND e.cid = c.cid
)
);Read it from the outside in, in plain words:
- Keep student
sif there is no coursec... - ...for which there is no enrollment row linking
stoc.
The middle query collects the courses the student is missing. The outer NOT EXISTS keeps the student only if that collection is empty.
Worked example
Take these tables:
- Student: sid 1, 2, 3
- Course: cid 10 (DB), 20 (OS)
- Enrolled: (1, 10), (1, 20), (2, 10)
| Student | Missing courses (middle query result) | Kept? |
|---|---|---|
| 1 | none | yes |
| 2 | 20 | no |
| 3 | 10 and 20 | no |
The result is the single row sid = 1.
Variations
A "for all" condition usually applies to a subset of the items, such as all courses with a certain name. Put that restriction in the WHERE of the middle query, next to the inner NOT EXISTS. The restriction defines the set the student must cover.
SELECT s.sid
FROM Student s
WHERE NOT EXISTS (
SELECT *
FROM Course c
WHERE c.cname LIKE 'DB%'
AND NOT EXISTS (
SELECT *
FROM Enrolled e
WHERE e.sid = s.sid AND e.cid = c.cid
)
);The counting alternative
You can also compare how many distinct courses a student took with how many courses exist.
SELECT e.sid
FROM Enrolled e
JOIN Course c ON c.cid = e.cid
GROUP BY e.sid
HAVING COUNT(DISTINCT e.cid) = (SELECT COUNT(*) FROM Course);The join to Course matters. Without it, an enrollment in a course that is not in Course would inflate the count. The foreign key in the CREATE TABLE statement normally prevents such rows, but a query should not rely on that when a join is cheap. DISTINCT guards against duplicate enrollment rows.
The two patterns differ on edge cases:
| Situation | Double NOT EXISTS | Counting version |
|---|---|---|
| Course table is empty | Returns every student, because no counterexample exists | Returns nothing, because every group has a count of at least 1 and the target is 0 |
| Student has no enrollments | Kept only if Course is empty | Never appears, because the student has no row in Enrolled |
| Restricting to a subset of courses | Add a condition to the middle query | Needs the same condition in both the join and the subquery count |
The first row is vacuous truth. "Every course" is trivially satisfied when there are no courses. GATE questions sometimes test this.
Common errors
- Missing correlation. If you drop
e.sid = s.sid, the innermost query ignores the student. It then asks only whether anyone is enrolled in the course. - Only one NOT EXISTS.
WHERE NOT EXISTS (SELECT * FROM Enrolled e WHERE e.sid = s.sid)finds students with no enrollments at all. It does not find students enrolled in everything. - Using NOT IN in the middle.
NOT INreturns nothing if the subquery yields a NULL. PreferNOT EXISTSfor this pattern. - Wrong direction. The outer table is the one whose rows you return (students), and the middle table is the set to be covered (courses). Swapping them returns courses that every student takes.
Exercise
Using Student(sid, sname, age), Course(cid, cname) and Enrolled(sid, cid), write a query for the sids of students who are enrolled in every course whose cname begins with 'DB'.
Show answer
SELECT s.sid FROM Student s WHERE NOT EXISTS (SELECT FROM Course c WHERE c.cname LIKE 'DB%' AND NOT EXISTS (SELECT FROM Enrolled e WHERE e.sid = s.sid AND e.cid = c.cid)); The restriction on cname goes in the middle query, and the innermost query is correlated on both s.sid and c.cid.
Exercise
Course has 3 rows and Enrolled has the rows (1,10), (1,20), (1,30), (2,10), (2,20). Student has sids 1, 2 and 3, and the courses are 10, 20 and 30. How many rows does the double NOT EXISTS query return, and which student is excluded for having no enrollments, even though the pattern could still be tested for them?
Show answer
One row, sid 1. Students 2 and 3 each have a missing course (30 for student 2, all three for student 3), so each has a counterexample. Student 3 has no enrollments, so the middle query returns all three courses for them.