EXISTS and NOT EXISTS in SQL
EXISTS asks whether any matching row exists, and stops at the first one.
SELECT
c.id,
c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
AND o.placed_at >= '2026-01-01'
)
ORDER BY c.name;
How it works
- It ignores what the subquery selects, only whether it returns a row.
NOT EXISTSis the safe way to sayhas none of these.- Unlike
NOT IN, it behaves sanely when NULLs are involved.
Keywords and builtins used here
ANDASBYEXISTSFROMNOTORDERSELECTWHEREc
The run, in numbers
- Lines
- 11
- Characters to type
- 162
- Tokens
- 44
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 29 seconds.
Step 3 of 3 in Subqueries, step 3 of 24 in Analytics & reporting.