Why does NOT IN return no rows?
NOT IN returns no rows when the list it checks against contains a NULL. SQL cannot say that a value is different from something unknown, so no row passes the test, and you get an empty result with no error. Use NOT EXISTS, or keep the NULLs out of the list.
How it usually happens
You want the customers who have never ordered. The query is one line and reads like English: customers whose id is not in the orders table. It worked last month. Then one order came in through guest checkout, with no customer attached, and now the same query returns nothing at all.
The tables
| id | name |
|---|---|
| 1 | Ana |
| 2 | Ben |
| 3 | Chloe |
| 4 | Dev |
| order_id | customer_id |
|---|---|
| 101 | 1 |
| 102 | 2 |
| 103 | NULL |
| 104 | 1 |
Order 103 has no customer. Chloe and Dev have never ordered.
The query that returns nothing
SELECT name
FROM customers
WHERE id NOT IN (
SELECT customer_id FROM orders
)
ORDER BY name;
It returns no rows. Chloe and Dev should be there.
Why one NULL empties the result
The subquery returns 1, 2, NULL and 1. For Chloe, whose id is 3, the database checks 3 <> 1 and 3 <> 2 and 3 <> NULL. The first two are true. The last one is unknown, because NULL means "we don't know the value", and it could be 3. True and true and unknown is unknown, and WHERE only keeps rows where the answer is true. The same happens for every customer.
The fix
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.id
)
ORDER BY c.name;
| name |
|---|
| Chloe |
| Dev |
NOT EXISTS asks a yes or no question for each customer: is there an order with this id? The order with no customer matches nobody, so it changes nothing.
If you prefer to keep NOT IN, add WHERE customer_id IS NOT NULL inside the subquery. It works, but you have to remember it every time.
Rule to remember: when the list comes from a subquery, write NOT EXISTS. NOT IN is safe with a list you typed yourself, like NOT IN (1, 2, 3).
Try it yourself
Same trap, different tables. A library lends books, and one loan was entered without a member.
| id | name |
|---|---|
| 1 | Iris |
| 2 | Jon |
| 3 | Kai |
| 4 | Lou |
| loan_id | member_id | book |
|---|---|---|
| 1 | 1 | Dune |
| 2 | NULL | Emma |
| 3 | 3 | Ulysses |
The query below is meant to list the members who have never borrowed a book, as name, sorted by name. It returns no rows. Fix it so it returns the two members.
Hint
Look at loan 2. What does the subquery return for it?
Show solution
SELECT m.name
FROM members m
WHERE NOT EXISTS (
SELECT 1 FROM loans l
WHERE l.member_id = m.id
)
ORDER BY m.name;| name |
|---|
| Jon |
| Lou |
MintQuery has 500+ exercises like this one, in lessons of a few minutes.
Start freeGet the app