EXISTS & Anti-join Patterns in SQL
NULL-immune existence — the safe NOT IN
EXISTS tests whether a correlated subquery returns any row — TRUE/FALSE, never UNKNOWN, immune to NULL poisoning, short-circuits on first match, ignores the SELECT list (SELECT 1 idiom). NOT EXISTS is the safe anti-join (employees without departments). LEFT JOIN … WHERE right.key IS NULL is equivalent and sometimes planner-friendlier. NOT IN is concise but poisoned: one NULL returns zero rows.
EXISTS is TRUE/FALSE
Correlated probe returning any row. Never UNKNOWN — NULL-immune. Short-circuits first hit.
NOT EXISTS anti-joins
Left rows with no match. The safe absence test.
LEFT/IS NULL mirrors
LEFT JOIN … WHERE right.key IS NULL — visible, sometimes planner-friendlier.
NOT IN poisons
One NULL in the set → zero rows, silent. Prefer NOT EXISTS; filter NULLs if forced.
1SELECT e.name FROM employees e WHERE NOT EXISTS (SELECT 1 FROM departments d WHERE d.dept_id = e.department);
| name |
|---|
Every employee matches a department, so the anti-join is empty — healthy signal. Add a Research orphan and she alone appears. NOT IN with a NULL in the set would have wrongly emptied even healthy matches.
Departments that HAVE staff
Existence without duplication.
1SELECT * FROM departments d WHERE EXISTS (SELECT 1 FROM employees e WHERE e.department = d.dept_id);
| dept_id | location |
|---|---|
| Engineering | Berlin |
| Sales | Madrid |
| Marketing | Lisbon |
Staff without departments (safe)
Empty here = healthy. NULL-proof.
1SELECT e.name FROM employees e WHERE NOT EXISTS (SELECT 1 FROM departments d WHERE d.dept_id = e.department);2-- unsafe twin: WHERE department NOT IN (SELECT dept_id FROM departments); -- NULL poisons
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.