capypad
0 day streak
sql / expert
Snippet

Relational Division via Cardinality Matching

Relational division identifies entities associated with every member of a specific set. Unlike the double-negation approach, cardinality matching counts distinct matches against the target set's size. This is essential for 'all-or-nothing' requirement queries.

snippet.sql
sql
1
2
3
4
5
SELECT student_id
FROM student_courses
WHERE course_id IN (101, 102, 103)
GROUP BY student_id
HAVING COUNT(DISTINCT course_id) = 3;
Breakdown
1
WHERE course_id IN (101, 102, 103)
Filters the initial dataset to only include the required attributes.
2
GROUP BY student_id
Aggregates the data by the candidate entity.
3
HAVING COUNT(DISTINCT course_id) = 3
Ensures the entity possesses exactly the number of unique items required (3 in this case).