sql / expert
Snippet
Relational Division via Double Negation
Relational division is used to identify entities that are associated with every record in a target set. Since SQL lacks a native 'DIVIDE' operator, we use double negation with NOT EXISTS to find projects where there is 'no skill that is not present in this project'.
snippet.sql
1
2
3
4
5
6
7
8
9
10
11
12
SELECT DISTINCT p.idFROM Projects pWHERE NOT EXISTS (SELECT s.idFROM Skills sWHERE NOT EXISTS (SELECT 1FROM Project_Skills psWHERE ps.project_id = p.idAND ps.skill_id = s.id));
Breakdown
1
WHERE NOT EXISTS (SELECT s.id FROM Skills s ...)
Starts the check for any skill that might be missing from the project.
2
WHERE NOT EXISTS (SELECT 1 FROM Project_Skills ps ...)
The inner negation checks if the specific project-skill relationship is absent.