Find the bug · #12 · Empty and null Hard SQL
The “come back” list is empty
A query for customers who never ordered returns nobody, though plenty never bought anything.
On this page
The report
Marketing wants to email customers who have never placed an order. The query returns no one, even though plenty of customers have never bought anything.
The code
Read it first: what should it do? Then click the line where you think the bug is.
-- Customers who have never ordered, for a "come back" email.
SELECT name
FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders)
ORDER BY name;Read it, then pick a line.
One order is a guest checkout with no customer. What does NOT IN do when its list contains a NULL?
What it prints
Run against the tables below, the query returns the rows on the left. It should return the rows on the right.
The tables
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER);
INSERT INTO customers VALUES (1, 'Asha'), (2, 'Ravi'), (3, 'Meera');
-- Order 12 was a guest checkout: no customer.
INSERT INTO orders VALUES (10, 1), (11, 1), (12, NULL);It returns
(no rows)
It should return
Meera Ravi
Show the answer: the bug, the fix, and how you’d find it
The bug (line 4)
Line 4 uses NOT IN with a subquery, and one order has a NULL customer. id NOT IN (1, 1, NULL) means id <> 1 AND id <> NULL, and a comparison with NULL is never true (it’s unknown). So no row passes and the query returns nothing. NOT EXISTS compares row by row and doesn’t have this problem.
The fix
1-- Customers who have never ordered, for a "come back" email.2SELECT name3FROM customers4WHERE id NOT IN (SELECT customer_id FROM orders)3FROM customers c4WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)5ORDER BY name;How you’d find it
- Run the query: no rows. Sanity check: Ravi and Meera have no orders, so they should be there.
- Run the subquery on its own: it returns 1, 1 and NULL. A NULL inside a
NOT INlist is the classic culprit. - Confirm it: add
WHERE customer_id IS NOT NULLto the subquery and the rows come back. Then useNOT EXISTS, which is safe with NULLs.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
-- should return:
-- Meera
-- RaviWhere else this bites
- Any
WHERE col NOT IN (subquery)on a column that allows NULL. WHERE discount <> 10also quietly skips the rows where discount is NULL.