Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

This query returns no rows even though many customers have no orders:

SQL
SELECT *
FROM customers
WHERE id NOT IN (SELECT customer_id
FROM orders);

Explain and fix it.

If even one orders.customer_id is NULL, id NOT IN (subquery) compares every customer id with that NULL, the comparison is UNKNOWN, and so the whole NOT IN is UNKNOWN for every row that has no order, and nothing is returned. The fix is NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id), which is not affected by NULLs and is planned as an efficient anti-join; LEFT JOIN orders o ON ... WHERE o.customer_id IS NULL also works. If a NULL customer_id is not valid data, make the column NOT NULL as well.

Why this question is asked

This is one of the classic SQL surprises: a query that is obviously correct returns an empty result, and nothing in the error log explains why. It comes from SQL's three-valued logic, and once we understand it, we avoid NOT IN with subqueries for good. Interviewers ask this to see whether we know how NULL behaves in comparisons and which rewrite is both correct and fast. In this answer, we will recap three-valued logic, reproduce the empty result, walk through why NOT IN fails, fix it with NOT EXISTS and with a LEFT JOIN, look at how each is planned, and fix the data model.

1A Quick Recap of NULL and Three-Valued Logic

In SQL, NULL means unknown or missing. A comparison with NULL does not return true or false; it returns a third value, UNKNOWN. 5 = NULL is UNKNOWN, and so is 5 <> NULL, because we cannot know whether an unknown value equals 5.

A WHERE clause keeps a row only when its condition is TRUE. Rows where it is FALSE or UNKNOWN are dropped. The logic operators follow the same rules: TRUE AND UNKNOWN is UNKNOWN, FALSE AND UNKNOWN is FALSE. That last detail is the whole story of this bug.

2Reproducing the Empty Result

Let us build a tiny example: three customers, of whom only customer 1 has an order, plus one order whose customer_id is NULL, for example a guest checkout or a bad import.

SQL
CREATE TABLE customers (id int PRIMARY KEY, name text);
CREATE TABLE orders (id int PRIMARY KEY, customer_id int); -- nullable
INSERT INTO customers VALUES (1,'Ann'), (2,'Bob'), (3,'Cy');
INSERT INTO orders VALUES (10, 1), (11, NULL);
SELECT * FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);
-- (0 rows) Bob and Cy have no orders, yet nothing is returned
DELETE FROM orders WHERE customer_id IS NULL;
SELECT * FROM customers WHERE id NOT IN (SELECT customer_id FROM orders);
-- 2 | Bob
-- 3 | Cy without the NULL, the query works

Notice that the query is correct as long as the subquery returns no NULL. A single NULL row among millions of orders silently turns the result into nothing.

3Why NOT IN Returns Nothing

id NOT IN (1, NULL) means id <> 1 AND id <> NULL. Let us evaluate it for Bob, whose id is 2.

Java
-- for Bob (id = 2), the subquery returns {1, NULL}
-- 2 NOT IN (1, NULL)
-- = (2 <> 1) AND (2 <> NULL)
-- = TRUE AND UNKNOWN
-- = UNKNOWN -> WHERE drops the row
-- for Ann (id = 1)
-- = (1 <> 1) AND (1 <> NULL)
-- = FALSE AND UNKNOWN
-- = FALSE -> dropped, correctly
NOT IN against a list containing NULL
Customerid <> 1id <> NULLResult
Ann (1)FALSEUNKNOWNFALSE, dropped (correct)
Bob (2)TRUEUNKNOWNUNKNOWN, dropped (bug)
Cy (3)TRUEUNKNOWNUNKNOWN, dropped (bug)

So customers with orders are dropped because their condition is FALSE, which is correct, and customers without orders are dropped because their condition is UNKNOWN, which is the bug. No row can ever be TRUE while the list contains a NULL, because the database can never be sure that an unknown customer_id is not equal to our id. SQL is being logically consistent; it is our query that asks the wrong question.

4Fix 1: NOT EXISTS

NOT EXISTS asks a different question: is there any order row whose customer_id equals this customer's id? For an order with a NULL customer_id, o.customer_id = c.id is UNKNOWN, which simply means that row does not match. It does not poison the whole answer.

Java
SELECT c.*
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
-- 2 | Bob
-- 3 | Cy
EXPLAIN SELECT c.* 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)
-- -> Seq Scan on customers c
-- -> Hash -> Seq Scan on orders o

Notice the Hash Anti Join. An anti-join is a join that returns the rows of one side that have no match on the other, which is exactly our question, and the planner can run it as a hash, merge or nested loop join using an index on orders(customer_id). With NOT IN, PostgreSQL cannot generally use an anti-join, because the NULL semantics differ, so it falls back to a hashed subplan or, if the subquery result is too large for memory, a plan that rescans the subquery per row, which can be very slow. So NOT EXISTS is the better choice for both correctness and speed.

5Fix 2: LEFT JOIN and IS NULL

The same anti-join can be written with an outer join. A LEFT JOIN keeps every customer and fills the order columns with NULL when there is no match, so we keep only those rows.

SQL
SELECT c.*
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.customer_id IS NULL;
-- 2 | Bob
-- 3 | Cy

The order with a NULL customer_id never matches any customer in the ON condition, so it cannot affect the result. We must test a column that is non-null in every real match, here o.customer_id itself or the primary key o.id. PostgreSQL usually recognises this pattern and plans it as the same anti-join. NOT EXISTS states the intent more directly, so it is the version most teams standardise on.

If we really want to keep NOT IN, adding WHERE customer_id IS NOT NULL inside the subquery also makes it correct, but it remains harder to optimise, so it is best kept for small lists.

6Fixing the Data Model

The query fix protects us, but it is worth asking why an order has no customer at all. If every order must belong to a customer, a NULL is bad data, and the column should be declared NOT NULL with a foreign key to customers. Then the database rejects such rows, the NOT IN trap cannot occur, and the planner can use that knowledge. If NULL is legitimate, such as guest orders, the model should make that explicit, and every query over the column must treat NULL deliberately.

SQL
UPDATE orders SET customer_id = :guest_customer_id WHERE customer_id IS NULL; -- or fix the rows
ALTER TABLE orders ALTER COLUMN customer_id SET NOT NULL;
ALTER TABLE orders ADD CONSTRAINT orders_customer_fk
FOREIGN KEY (customer_id) REFERENCES customers (id);

7Follow-up questions

Does the same problem happen with IN?

Not in the same way. id IN (1, NULL) is id = 1 OR id = NULL, so for Ann it is TRUE OR UNKNOWN, which is TRUE, and she is returned. For Bob it is FALSE OR UNKNOWN, which is UNKNOWN, so he is dropped, which is what we want anyway. IN gives the expected rows; only the negation, NOT IN, turns UNKNOWN into a missing result.

Is this specific to PostgreSQL?

No. Three-valued logic is part of the SQL standard, so NOT IN behaves the same way in MySQL, Oracle and SQL Server. The planning differences vary, but the empty result is universal, which is why NOT EXISTS is the portable recommendation.

How would I write this in JPA?

JPQL supports NOT EXISTS with a correlated subquery, such as SELECT c FROM Customer c WHERE NOT EXISTS (SELECT o FROM Order o WHERE o.customer = c), and the Criteria API has cb.not(cb.exists(subquery)). Both generate an SQL NOT EXISTS, so we get the same correct and efficient anti-join.

8Conclusion

In this answer, we saw that NOT IN with a subquery returns no rows when the subquery contains a NULL, because id <> NULL is UNKNOWN, and TRUE AND UNKNOWN is UNKNOWN, which WHERE drops. We fixed it with NOT EXISTS, which treats a NULL row as simply not matching and is planned as an anti-join, and with an equivalent LEFT JOIN ... WHERE o.customer_id IS NULL. Finally, we made customer_id NOT NULL with a foreign key where a missing customer is not valid data.

What to say in the interviewAbout 100 seconds aloud

Open with

The query looks right, but it breaks as soon as one order has a NULL customer_id. NOT IN with a list means the id is not equal to every value in the list, so it becomes id not equal to 1 AND id not equal to NULL, and so on.

Then, if they want more

Any comparison with NULL is UNKNOWN in SQL's three-valued logic. For a customer without orders, every real comparison is TRUE, but TRUE AND UNKNOWN is UNKNOWN, and WHERE only keeps rows where the condition is TRUE. So every customer without orders is dropped, and customers with orders are dropped anyway because one comparison is FALSE. The result is empty.

The fix is NOT EXISTS: WHERE NOT EXISTS, select 1 from orders where o.customer_id equals c.id. That asks whether any matching order exists, and a NULL customer_id simply does not match, so it does no harm.

It is also planned as an anti-join, a hash or merge anti join or a nested loop using an index on orders customer_id, which is usually efficient, while NOT IN often cannot be turned into an anti-join because of exactly these NULL semantics.

An alternative is a LEFT JOIN to orders with WHERE o.customer_id IS NULL, which gives the same result. I would also ask why an order has no customer. If that is not valid, I would clean the data and make the column NOT NULL with a foreign key, so the problem cannot come back.

About this answer

Last updated
12 November 2026
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 even though many customers have no orders:": https://scrivio-interview-library.netlify.app/databases/query-optimization/79f917f980/