Tech challenge · SQL
The "customers without orders" report is empty
This query should list customers who have never ordered. It worked for months, and today it returns no rows at all, although you know such customers exist:
SELECT customer_id FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders);What changed, and how do you fix it for good?
Think it through or sketch an answer first, then open the hint or the solution.
Show a hint
Think about what happens when one value in the subquery is NULL.
Show the solution
One order row now has a NULL customer_id (a guest checkout, say). x NOT IN (1, 2, NULL) means x <> 1 AND x <> 2 AND x <> NULL, and the last comparison is UNKNOWN, so no row passes. Use NOT EXISTS, which is not affected by NULLs and is usually planned as an efficient anti-join.
Example (SQL)
SELECT c.customer_id
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
Common mistakes
- Adding WHERE customer_id IS NOT NULL to the subquery fixes today's data but leaves the trap for the next query someone writes.
- Switching to a LEFT JOIN but testing a nullable column of orders for IS NULL instead of the join key.
How did you do? Your answer is saved in this browser and comes back for revision later.