EXISTS and NOT EXISTS: test for related rows
Overview
EXISTS tests whether a subquery returns any row, and NOT EXISTS tests whether it returns none. They filter outer rows without multiplying them for repeated inner matches.
First example
SELECT c.id, c.name FROM customers cWHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)ORDER BY c.id;Observed SQLite result (rows in JSON):
[ [ 1, "Alice" ], [ 2, "David" ]]How it works
The first query finds customers who placed an order; the second finds products never purchased. SELECT 1 is conventional because only row existence matters in these simple queries. EXISTS (SELECT NULL) is true: a row exists even when its value is NULL. NOT EXISTS with an equality condition is not universally equivalent to NOT IN because NULL can make the latter unknown. An inner COUNT(*) without GROUP BY returns one row even for empty input, so wrapping that aggregate directly in EXISTS is not an emptiness test. Do not assume all inner rows will be evaluated.
Practical example
SELECT p.id, p.name FROM products pWHERE NOT EXISTS (SELECT 1 FROM order_items i WHERE i.product_id = p.id)ORDER BY p.id;Observed SQLite result (rows in JSON):
[ [ 4, "Pencil" ]]Practice and mistakes
Practice: find customers without orders (Sara). Compare NOT EXISTS and NOT IN against the nullable thresholds fixture using an outer price of 350; explain why absence of a match is not the same as all comparisons being false.