In two sentences
EXISTS keeps a row when at least one matching row exists somewhere else; NOT EXISTS keeps it when none does.
Unlike a join, they never multiply rows and never bring columns along: they only answer yes or no for each row.
See it
| customer_id |
|---|
| c1 |
| c2 |
| c3 |
| order_id | customer_id |
|---|---|
| 1 | c1 |
| 2 | c1 |
| 3 | c2 |
| 4 | NULL ← guest checkout |
| question | query | result |
|---|---|---|
| customers with orders | JOIN orders | c1, c1, c2 |
| customers with orders | WHERE EXISTS (…) | c1, c2 |
| customers without orders | WHERE NOT EXISTS (…) | c3 |
| customers without orders | LEFT JOIN … WHERE o.order_id IS NULL | c3 |
| customers without orders | WHERE customer_id NOT IN (SELECT customer_id FROM orders) | nothing |
The join returns c1 twice because c1 has two orders. NOT IN returns nothing because of the guest order's NULL.
In SQL
Customers who ordered (a semi-join):
SELECT c.customer_id
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);Customers who never ordered (an anti-join):
SELECT c.customer_id
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id);Orders pointing at a customer that doesn't exist: a referential-integrity check.
SELECT o.*
FROM orders o
WHERE o.customer_id IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM customers c WHERE c.customer_id = o.customer_id);Insert only the rows that aren't there yet, so a re-run adds nothing:
INSERT INTO dim_customer (customer_id, name)
SELECT s.customer_id, s.name
FROM staging_customers s
WHERE NOT EXISTS (SELECT 1 FROM dim_customer d WHERE d.customer_id = s.customer_id);Common mistakes
NOT INover a column that can be NULL. One NULL in the subquery makes every comparison unknown, and the query returns nothing. UseNOT EXISTS. See NULLs and missing values.- Using
JOINfor "has at least one". The join repeats the row once per match; then someone addsDISTINCTto hide it.EXISTSsays what you mean. - Forgetting the correlation.
EXISTS (SELECT 1 FROM orders)withoutWHERE o.customer_id = c.customer_idis true for every customer as soon asordershas a row. LEFT JOIN … IS NULLon the wrong column. Test a column that is never NULL on a matching row (the key you joined on, or a primary key), not one that can be NULL anyway.
What an interviewer asks next
- "
NOT IN,NOT EXISTSorLEFT JOIN … IS NULL?"NOT EXISTS: correct with NULLs, and engines run it as an anti-join.LEFT JOIN … IS NULLis also correct;NOT INis the trap. - "Make this insert safe to re-run."
INSERT … SELECT … WHERE NOT EXISTS, or aMERGE.
Go further
PostgreSQL's page on subquery expressions spells out exactly when IN and NOT IN return NULL; Trino behaves the
same way.
Practise it
Find Orphaned Orders Before They Reach the Dashboard, then The Churn Report Returns Zero Rows: NULL Semantics for the NOT IN trap, then Facts Before
Their Dimension: Inferred Members.