One NULL in a subquery made our NOT IN report return zero customers
The weekly report of customers who had never ordered suddenly came back empty. Nobody had changed the query. One order row with a NULL customer_id had arrived, and SQL's three-valued logic did the rest. Why NOT IN behaves this way, and why NOT EXISTS is the safe default.
Every Monday, the marketing team receives a list of customers who signed up but never placed an order, for a reminder campaign. It usually has a few thousand rows. One Monday it had none. The job had run without error, the export file had a header and no data, and the campaign tool happily sent nothing.
The query had not changed in over a year:
SELECT c.id, c.email, c.created_at
FROM customers c
WHERE c.created_at >= now() - interval '90 days'
AND c.id NOT IN (SELECT o.customer_id FROM orders o);
Running it by hand returned zero rows. Running the pieces separately did not add up:
SELECT count(*) FROM customers WHERE created_at >= now() - interval '90 days';
-- 41207
SELECT count(DISTINCT customer_id) FROM orders;
-- 18334
Forty thousand recent customers, and far fewer than that had any orders. The answer could not be zero.
Finding the NULL
When NOT IN returns nothing unexpectedly, the first thing to check is whether the subquery contains a
NULL:
SELECT count(*) FROM orders WHERE customer_id IS NULL;
-- 1
One row. It had been created the previous Friday by a new guest checkout feature, which stored orders without a customer account. The column had always allowed NULL; until that feature, nothing had ever written one.
Excluding it brought the report back:
... AND c.id NOT IN (SELECT o.customer_id FROM orders o WHERE o.customer_id IS NOT NULL);
-- 22874 rows
Three-valued logic
SQL comparisons do not return only true or false. When either side is NULL, a comparison returns
unknown. NULL means "value not known", so the database cannot say whether 5 = NULL is true; it might
be, if the unknown value happened to be 5.
A WHERE clause keeps a row only when its condition is true. False and unknown are both filtered out.
How NOT IN expands
x NOT IN (a, b, c) is defined as x <> a AND x <> b AND x <> c. With a NULL in the list:
c.id NOT IN (17, 42, NULL)
= c.id <> 17 AND c.id <> 42 AND c.id <> NULL
= true AND true AND unknown -- for a customer with id 5
= unknown
true AND unknown is unknown, so the condition is never true for any customer whose ID is not in the
list. And for a customer whose ID is in the list, one comparison is false, so the whole thing is false.
Every row ends up either false or unknown, and the result is empty.
One NULL anywhere in the subquery is enough. That is why the report went from thousands of rows to zero overnight, not to slightly fewer.
IN does not have this problem in the same way: x IN (17, 42, NULL) is x = 17 OR x = 42 OR x = NULL,
and true OR unknown is true, so matches are still found. It is specifically the negation that breaks.
Why NOT EXISTS behaves differently
NOT EXISTS asks a different question: does the subquery return any row for this customer?
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
For each customer, the subquery looks for orders with a matching customer_id. The NULL row never matches
= c.id (that comparison is unknown, so the row is not returned), and it does not affect any other
customer. A subquery either returns rows or it does not; there is no unknown at the EXISTS level.
Same on every engine
We checked the behaviour on both databases we run, because people sometimes expect one of them to be "smarter":
| Engine | NOT IN with NULL in subquery |
NOT EXISTS |
|---|---|---|
| PostgreSQL 16 | 0 rows | 22,874 rows |
| MySQL 8.0 | 0 rows | 22,874 rows |
This is standard SQL behaviour, not a bug in either engine.
Environment
| Item | Value |
|---|---|
| Database | PostgreSQL 16 (production), MySQL 8.0 (tested for comparison) |
| Tables | customers 2.1M rows, orders 9.4M rows |
| Trigger | guest checkout writing orders.customer_id = NULL |
| Symptom | report returned 0 rows with no error |
1. Rewrite with NOT EXISTS
SELECT c.id, c.email, c.created_at
FROM customers c
WHERE c.created_at >= now() - interval '90 days'
AND NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.id
);
This is correct whether or not orders.customer_id contains NULLs, and it states the intent directly:
customers for whom no order exists.
The equivalent anti-join form, which some people find easier to read:
SELECT c.id, c.email, c.created_at
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE c.created_at >= now() - interval '90 days'
AND o.id IS NULL;
Test o.id, the primary key, which can only be NULL when there was no matching row. Testing a nullable
column like o.customer_id would reintroduce ambiguity.
2. Performance
All three forms can be fast; the question is whether the planner recognises them as an anti-join. On PostgreSQL 16:
-- NOT EXISTS
Hash Right Anti Join (actual time=812.4..1290.6 rows=22874 loops=1)
Hash Cond: (o.customer_id = c.id)
-> Seq Scan on orders o (actual rows=9412003)
-> Hash (actual rows=41207)
-> Index Scan using customers_created_at_idx on customers c
Execution Time: 1296.1 ms
-- NOT IN (with the IS NOT NULL filter added)
Seq Scan on customers c (actual time=1544.2..2401.9 rows=22874 loops=1)
Filter: (NOT (hashed SubPlan 1))
SubPlan 1
-> Seq Scan on orders o Filter: (customer_id IS NOT NULL)
Execution Time: 2419.7 ms
PostgreSQL turns NOT EXISTS into an anti-join, but it cannot do the same for NOT IN because the NULL
semantics are different, so NOT IN is planned as a hashed subplan. Here it was about twice as slow, and
if the subquery result is too large for work_mem, PostgreSQL falls back to a plain subplan that
re-scans per row, which can be catastrophically slow. An index on orders (customer_id) let the
NOT EXISTS version use an index-only scan and dropped it to about 180 ms.
MySQL 8.0 can convert both NOT EXISTS and NOT IN (when it can prove the columns are not nullable) into
anti-joins. With a nullable column it cannot, which is one more reason to prefer NOT EXISTS.
3. Fix the data model too
The guest checkout feature was legitimate, but NULL was the wrong way to represent it. "No customer
account" is a known fact, not an unknown value. We added a guest_checkout_id column and a check
constraint that exactly one of customer_id and guest_checkout_id is set. NULLs in customer_id are
still possible, so NOT EXISTS stays, but every row now says explicitly which kind of order it is.
4. Find other NOT IN queries
grep -rniE "not\s+in\s*\(\s*select" app/ reports/ sql/
This turned up eleven more queries. Seven were against columns declared NOT NULL and therefore safe
today; we rewrote them anyway so a future schema change cannot break them silently. Four were against
nullable columns.
1. A regression test with a NULL in the data.
BEGIN;
INSERT INTO customers (id, email, created_at) VALUES (900001, 'a@example.com', now()),
(900002, 'b@example.com', now());
INSERT INTO orders (id, customer_id) VALUES (800001, 900001), (800002, NULL);
-- expect exactly customer 900002
SELECT id FROM customers c
WHERE c.id IN (900001, 900002)
AND NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
ROLLBACK;
It returns 900002. The old NOT IN form returns nothing for the same data. We run it in the report
job's test suite.
2. Row count monitoring. The report job now fails if its row count drops more than 80 percent compared to the previous week, rather than sending an empty campaign. A sudden drop to zero is far more likely to be a bug than a real change.
3. Linting. Our SQL linter, SQLFluff, does not flag NOT IN with a subquery by default, so we added a
custom rule in the review checklist: NOT IN (SELECT ...) requires a reviewer to confirm the column is
NOT NULL, or it is rewritten to NOT EXISTS.
4. Security implications. Beyond the missed campaign, the same pattern matters in access control: queries like "users NOT IN (SELECT user_id FROM blocked_users)" fail in the dangerous direction for an allow list or the safe direction for a deny list, depending on how they are written. We audited the four nullable cases and confirmed none controlled access.
Takeaways
x NOT IN (subquery)returns no rows if the subquery yields a single NULL.NOT EXISTS(or aLEFT JOIN ... IS NULLon a primary key) is correct regardless of NULLs.NOT EXISTSis also more likely to be planned as an efficient anti-join.- Alert on sudden drops in report row counts. An empty result is rarely the truth.
References: PostgreSQL subquery expressions, PostgreSQL comparison operators and NULL, MySQL anti-join optimization.
Add a label
Embed this post
<iframe src="https://hibug.me/not-in-subquery-null-returns-no-rows" width="700" height="420" frameborder="0" loading="lazy"></iframe>
I started as an application developer and drifted toward the database because that is where our incidents kept ending up. For the last eight years I have looked after PostgreSQL and MySQL clusters for e-commerce and SaaS teams, from schema reviews to late-night failovers. Relational databases are well documented, yet the same surprises keep catching good engineers: a NOT IN that returns nothing because of one NULL, an index silently skipped after a type conversion, a FOR UPDATE that locked far more than intended, a replica that disagreed with its primary after promotion. In each post I reproduce the problem on a small dataset, read the plan or lock output together with you, explain the rule behind it and show the fix with numbers before and after. Where engines differ, I run the same test on both and show the results side by side.
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.