Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

This query returns no rows, but you know some customers have no orders: SELECT * FROM customers WHERE id NOT IN (SELECT customer_id FROM orders). Explain why and fix it.

At least one row in orders has customer_id NULL. id NOT IN (1, 2, NULL) means id <> 1 AND id <> 2 AND id <> NULL, and a comparison with NULL is UNKNOWN rather than TRUE, so the whole condition is never TRUE and every customer is filtered out. The fix is NOT EXISTS, which is not affected by NULLs in the subquery, or adding WHERE customer_id IS NOT NULL to the subquery, and making the column NOT NULL if an order must always have a customer.

Why this question is asked

This is one of the most common SQL bugs, and one of the most confusing the first time we meet it: the query is short, the logic reads correctly, and we can see customers without orders in the data, yet the result is empty. Interviewers ask it because the explanation requires understanding SQL's three-valued logic, which also causes many quieter bugs. In this answer, we will reproduce the problem, evaluate the condition by hand to see exactly where it goes wrong, fix it in two ways, and look at why NOT IN is also a poor choice for performance in PostgreSQL.

1Reproducing the Problem

Let us build three customers, two of whom have orders, plus one guest order with no customer. The guest order is the kind of row that appears when a checkout flow allows guests, or when an import could not match a customer.

SQL
CREATE TABLE customers (id int PRIMARY KEY, name text);
CREATE TABLE orders (id int PRIMARY KEY, customer_id int);
INSERT INTO customers VALUES (1, 'Ada'), (2, 'Ben'), (3, 'Cy');
INSERT INTO orders VALUES (10, 1), (11, 2);
SELECT * FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);
-- 3 | Cy -- correct while there are no NULLs
INSERT INTO orders VALUES (12, NULL); -- a guest order
SELECT * FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);
-- (0 rows) -- Cy has disappeared

One harmless-looking row changed the result for every customer. Nothing in the query refers to guest orders, which is exactly why this bug is so hard to spot.

2Why a Single NULL Removes Every Row

SQL uses three-valued logic. A condition can be TRUE, FALSE or UNKNOWN, and NULL means 'unknown value'. Any comparison with NULL, such as 3 = NULL or 3 <> NULL, gives UNKNOWN, because we cannot say whether an unknown value equals 3. A WHERE clause keeps a row only when the condition is TRUE; FALSE and UNKNOWN both remove it.

Now expand NOT IN. x NOT IN (a, b, c) is defined as x <> a AND x <> b AND x <> c. For Cy, that is 3 <> 1 AND 3 <> 2 AND 3 <> NULL, which is TRUE AND TRUE AND UNKNOWN. In three-valued logic, TRUE AND UNKNOWN is UNKNOWN, so the whole condition is UNKNOWN and Cy is removed. For Ada, 1 <> 1 is FALSE, so she is removed too, as intended. No row can ever reach TRUE while the list contains a NULL.

SQL
SELECT 3 NOT IN (1, 2); -- true
SELECT 3 NOT IN (1, 2, NULL); -- null (UNKNOWN), so WHERE drops the row
SELECT 1 NOT IN (1, 2, NULL); -- false
SELECT 3 IN (1, 2, NULL); -- null, not false
Evaluating 3 NOT IN (1, 2, NULL)
ComparisonResult
3 <> 1TRUE
3 <> 2TRUE
3 <> NULLUNKNOWN
TRUE AND TRUE AND UNKNOWNUNKNOWN -> row removed

Notice the last line: IN has the mirror problem, returning UNKNOWN instead of FALSE when the value is not found and a NULL is present. In a WHERE clause that still drops the row, so IN usually behaves as expected, but inside NOT (...) or in a CASE expression it can surprise us too.

3Fix 1: Use NOT EXISTS

NOT EXISTS asks a different question: is there an order row whose customer_id equals this customer's id? For the guest order, NULL = 3 is UNKNOWN, so that row is not a match, and it is simply ignored. The result depends only on rows that actually match.

SQL
SELECT c.* FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
-- 3 | Cy -- correct with or without NULL customer_ids

This is the fix I would choose by default, because it is correct whatever the data contains and it is the form planners handle best. It also reads naturally as 'customers for whom no order exists'.

4Fix 2: Exclude NULLs, and Fix the Data Model

If we want to keep NOT IN, we must make sure the subquery cannot return NULL. Adding a filter does that.

SQL
SELECT * FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders WHERE customer_id IS NOT NULL);
-- 3 | Cy
-- If every order must have a customer, say so in the schema:
ALTER TABLE orders ALTER COLUMN customer_id SET NOT NULL; -- fails while the guest row exists

The filter works, but it relies on every future author remembering it. The schema question is more important: should an order without a customer exist at all? If guest orders are legitimate, the column is rightly nullable and NOT EXISTS is the safe pattern. If they are not, the NULL row is bad data, and a NOT NULL constraint, after cleaning the rows, prevents both the bug and the data problem. A foreign key from orders.customer_id to customers.id is worth adding as well, since it stops orders from pointing at customers that do not exist.

5NOT IN Is Also Slower in PostgreSQL

There is a second reason to avoid NOT IN with a subquery. Because its NULL semantics differ from an anti-join, PostgreSQL cannot turn it into an Anti Join node. It runs it as a SubPlan. If the subquery result fits in work_mem, it builds a hash of it once, a hashed SubPlan, which is acceptable. If the result is too large, it falls back to a plain SubPlan that searches the subquery result for every outer row, and a query that was fast on test data can take hours in production. NOT EXISTS gets a proper Anti Join with nested loop, hash or merge strategies and an estimate the planner can reason about.

SQL
EXPLAIN SELECT * FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);
-- Seq Scan on customers
-- Filter: (NOT (hashed SubPlan 1)) -- or plain SubPlan 1 when the result is too big
EXPLAIN SELECT * FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
-- Hash Anti Join
-- Hash Cond: (c.id = o.customer_id)

NOT IN with a short literal list, such as status NOT IN ('cancelled', 'refunded'), is fine, as long as the list cannot contain NULL. The rule is about subqueries, where we do not control what comes back.

6Follow-up questions

Does the same thing happen in MySQL and other databases?

Yes. Three-valued logic is part of the SQL standard, so NOT IN with a NULL in the list returns no rows in MySQL, Oracle and SQL Server as well. MySQL 8.0.17 and later can execute NOT IN as an anti-join, but it must still respect the NULL rule, so the result is the same; only the speed differs.

Why does LEFT JOIN ... WHERE o.id IS NULL work correctly here?

The guest order has customer_id NULL, so it never joins to any customer, and each customer without orders gets a joined row with all order columns NULL. Testing o.id IS NULL, where id is the primary key and can only be NULL when there was no match, finds those customers. It is correct, but we must test a column that cannot be NULL in a real match, or the test gives false positives.

How would you catch this kind of bug in tests?

By putting NULLs in the test data on purpose. A fixture for orders should include a row with customer_id NULL whenever the column allows it, and the test for 'customers without orders' should assert that Cy is returned. Bugs like this survive because the test data was cleaner than production.

7Conclusion

In this answer, we saw that NOT IN expands into a chain of <> comparisons joined by AND, that a comparison with NULL is UNKNOWN, and that one NULL in the subquery therefore makes the condition UNKNOWN for every row, so nothing is returned. We fixed it with NOT EXISTS, which ignores NULLs, or by filtering NULLs out and making the column NOT NULL when that fits the model, and we saw that NOT IN with a subquery also plans as a SubPlan in PostgreSQL rather than an anti join.

What to say in the interviewAbout 90 seconds aloud

Open with

This happens because at least one order has a NULL customer_id, say a guest order. NOT IN expands to id <> each value, joined by AND. For a customer with id 3 and a list 1, 2, NULL, we get true and true and 3 <> NULL.

Then, if they want more

SQL has three-valued logic, so a comparison with NULL is unknown, not true, and true AND unknown is unknown. WHERE keeps only rows where the condition is true, so every customer is filtered out, including the ones without orders. One NULL in the subquery is enough to empty the result.

The fix I would use is NOT EXISTS: WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id). A NULL customer_id never equals anything, so that row is simply not a match and it does not affect the result. If someone wants to keep NOT IN, the subquery needs WHERE customer_id IS NOT NULL.

I would also ask whether orders without a customer should exist. If not, clean the rows and make the column NOT NULL with a foreign key, which removes the bug and the bad data.

There is a performance side too: PostgreSQL cannot turn NOT IN with a subquery into an anti-join because of those NULL semantics, so it runs a SubPlan, hashed if it fits in memory and per row if not, while NOT EXISTS gets a proper Anti Join.

About this answer

Last updated
12 November 2026
Versions it names
MySQL 8.0
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "This query returns no rows, but you know some customers have no orders: SELECT * FROM...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/212fdc4f71/