Why it happens: NOT IN does not return the expected rows
The query seems to say “return customers whose id is not in the list”. However, a single NULL row in the set can stop the condition from ever being true for the ids that do not match.
WITH exclusion_list(customer_id) AS (
VALUES (1), (3), (NULL)
)
SELECT id, name
FROM customers
WHERE id NOT IN (
SELECT customer_id
FROM exclusion_list
)
ORDER BY id;| rows returned |
|---|
| 0 |
Ids 2, 4, 5… are not in the list, but comparing them with the unknown item means SQL cannot conclude they are “different from all of them”.
How to fix it in SQL
Fix 1: remove NULL from the set if it is not a valid exclusion
WITH exclusion_list(customer_id) AS (
VALUES (1), (3), (NULL)
)
SELECT id, name
FROM customers
WHERE id NOT IN (
SELECT customer_id
FROM exclusion_list
WHERE customer_id IS NOT NULL
)
ORDER BY id;| id | name |
|---|---|
| 2 | Liam Martin |
| 4 | David Clark |
| 5 | Sara Green |
| 6 | Peter Hill |
| 7 | Laura Ward |
| 8 | Hugh Miller |
| 9 | Nia Smith |
| 10 | Jack Wood |
| 11 | Emily Fox |
| 12 | Miles Lee |
This solution is correct when NULL in the source means “no exclusion id” and should therefore be ignored.
Fix 2: express the missing match with NOT EXISTS
If what you really mean is “there is no exclusion row matching this customer”, NOT EXISTS says exactly that. A NULL in some other row does not create a comparison against every value.
WITH exclusion_list(customer_id) AS (
VALUES (1), (3), (NULL)
)
SELECT c.id, c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1
FROM exclusion_list AS e
WHERE e.customer_id = c.id
)
ORDER BY c.id;With this data it returns the same ten rows as the NOT IN with IS NOT NULLversion. Do not pick a form out of habit: pick the one that states the data rule most clearly.
How to check it
Run the subquery on its own and check it for NULLs. Test a key that is missing, one that is excluded and, if possible, a NULL key on the outer side.
How to avoid it next time
NOT EXISTS and NOT IN can behave differently when the outer key is NULL.
Related cases worth checking
- If an exclusion key should never be null, enforce that with a suitable constraint in the model.
- If
NULLis valid, handle that possibility explicitly in membership queries. - When the question is whether a related row exists, consider
EXISTS/NOT EXISTS. - Do not replace the diagnosis with
COALESCEto a made-up value unless that value has a real meaning and cannot clash with valid data.