MintQueryStart free
← All guides

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

customers
idname
1Ana
2Ben
3Chloe
4Dev
orders
order_idcustomer_id
1011
1022
103NULL
1041

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.

members
idname
1Iris
2Jon
3Kai
4Lou
loans
loan_idmember_idbook
11Dune
2NULLEmma
33Ulysses

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