capypad
0 day streak
sql / expert
Snippet

Relational Division via Double Negation

This pattern implements universal quantification (the 'FOR ALL' operator) using relational algebra. It identifies entities (students) that are associated with every entry in a target set (courses) by ensuring there is no course that the student has not enrolled in. This is more robust than COUNT-based comparisons as it handles set relationships purely through logic.

snippet.sql
sql
1
2
3
4
5
6
7
8
9
10
11
12
SELECT s.name
FROM students s
WHERE NOT EXISTS (
SELECT c.id
FROM courses c
WHERE NOT EXISTS (
SELECT 1
FROM enrollment e
WHERE e.student_id = s.id
AND e.course_id = c.id
)
);
Breakdown
1
SELECT s.name FROM students s
Selects the candidate records from the primary entity table.
2
WHERE NOT EXISTS (SELECT c.id FROM courses c ...)
Filters for entities where there is no record in the requirements set...
3
WHERE NOT EXISTS (SELECT 1 FROM enrollment e ...)
...for which a matching relationship record does not exist in the junction table.