Sub topic 4
NOT IN and NULL: a common trap
This chapter assumes you can write IN subqueries, you know how WHERE keeps only rows whose condition is true, and you understand NULL and three-valued logic (true, false, unknown). It covers one bug: NOT IN can return no rows at all when the subquery returns a NULL.
The query that looks right
Suppose you want customers who have never placed an order. The natural query uses NOT IN:
SELECT c.name
FROM customers c
WHERE c.id NOT IN (SELECT o.customer_id FROM orders o);The query reads correctly and passes review. It also works in testing, until orders.customer_id contains one NULL. After that it returns an empty result, with no error and no warning.
A reproducible example
Create two small tables. The customer_id column in orders allows NULL, which is the default when you don't write NOT NULL.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER,
total INTEGER NOT NULL
);
INSERT INTO customers (id, name) VALUES (1, 'Ana'), (2, 'Ben'), (3, 'Cy');
INSERT INTO orders (id, customer_id, total) VALUES
(10, 1, 50),
(11, 1, 120);Only Ana has orders, so the query returns Ben and Cy. Now add an order that has no customer, perhaps a guest checkout or a row from a bad import:
INSERT INTO orders (id, customer_id, total) VALUES (12, NULL, 30);Run the NOT IN query again. It now returns zero rows. Ben and Cy still have no orders, but they have disappeared from the result.
Why it happens
x NOT IN (a, b, c) is shorthand for a chain of inequalities joined with AND:
x <> a AND x <> b AND x <> cThe subquery in the example returns the list (1, 1, NULL). For Ben (id = 2), the expansion is:
2 <> 1 AND 2 <> 1 AND 2 <> NULLThe first two comparisons are true. The third is 2 <> NULL, and any comparison with NULL is unknown, not true or false. The AND rules finish the job:
| Left | Right | `AND` result |
|---|---|---|
| true | true | true |
| true | unknown | unknown |
| false | unknown | false |
| unknown | unknown | unknown |
So true AND true AND unknown is unknown. WHERE keeps a row only when the condition is true, so Ben is discarded. Cy is discarded the same way.
Ana is discarded for a different reason. Her 1 <> 1 is false, and false AND unknown is false. That is the correct answer for Ana.
The result depends on whether the value is in the list:
| Left value | Compared with `(1, NULL)` | `NOT IN` result | Row kept? |
|---|---|---|---|
| 1 | `1 <> 1` is false, so the AND is false | false | No |
| 2 | `2 <> 1` is true, `2 <> NULL` is unknown, so the AND is unknown | unknown | No |
| 3 | same as 2 | unknown | No |
When the list contains a NULL, no value can ever make NOT IN true. The best outcome for a value that is absent from the list is unknown, and WHERE treats unknown like false.
Other forms of the same trap
The same logic applies in several situations.
- Literal lists.
WHERE x NOT IN (1, 2, NULL)always returns no rows. This is rare in hand-written code, but it happens when an application builds the list from variables and one of them is NULL. - NULL on the left side. If
c.idis NULL and the subquery returns at least one row,NULL NOT IN (...)is unknown, so that row is dropped. This is usually what you want, but it is worth knowing. - An empty subquery. If the subquery returns no rows,
NOT INis true for every outer row, including those where the left value is NULL. An empty list has no comparisons that could be unknown. - Plain IN.
x IN (1, NULL)is true whenxis 1 and unknown otherwise. In aWHEREclause, unknown and false give the same result, soINseems to ignore the NULL. The trouble starts only when you negate it, becauseNOT unknownis still unknown.
Oracle treats an empty string as NULL, so on that platform a nullable text column can contain NULL values you did not insert on purpose.
Fix 1: use NOT EXISTS
NOT EXISTS is the most reliable fix. The correlated subquery only asks whether a matching row exists, and it uses an equality test whose unknown results are simply "no match".
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
);For Ben, the subquery finds no row where o.customer_id = 2. The comparison with the NULL row is unknown, so that row does not match, and NOT EXISTS is true. The query returns Ben and Cy whatever NULLs the table holds. The next chapter on EXISTS covers this form in detail.
Fix 2: remove NULLs from the subquery
If you want to keep NOT IN, filter the NULLs out where the list is built:
SELECT c.name
FROM customers c
WHERE c.id NOT IN (
SELECT o.customer_id
FROM orders o
WHERE o.customer_id IS NOT NULL
);This works, but it relies on every author remembering the filter. A later edit that drops the WHERE brings the bug back. A column that is nullable today may also be changed or joined differently tomorrow.
Fix 3: use an anti-join
A LEFT JOIN followed by a test for no match gives the same answer without a subquery:
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;Test a column that can never be NULL in a real order row, such as the primary key o.id. Testing a nullable column like o.total is only safe because that one is NOT NULL, and testing o.customer_id would be wrong in general.
Fix 4: make the data say what you mean
If an order must always have a customer, enforce it:
ALTER TABLE orders ALTER COLUMN customer_id SET NOT NULL;The syntax for changing a column varies by database; this form works in PostgreSQL. With the constraint in place, the NULL cannot be inserted and NOT IN is safe. Many teams still prefer NOT EXISTS as a habit, because the query stays correct if the constraint is later relaxed.
Choosing a fix
| Approach | Safe with NULLs | Notes |
|---|---|---|
| `NOT EXISTS` | Yes | Default choice. Handles NULLs by design. |
| `NOT IN` with `IS NOT NULL` filter | Yes | Correct, but easy to break when editing. |
| `LEFT JOIN ... IS NULL` | Yes | Test a non-nullable column from the right table. |
| `NOT IN` with a `NOT NULL` column | Yes | Depends on the constraint staying in place. |
| `NOT IN` on a nullable column | No | Returns no rows once a NULL appears. |
Spotting the bug in practice
When a "find rows with no match" query unexpectedly returns nothing, check for NULLs in the subquery's column:
SELECT COUNT(*) AS null_rows
FROM orders
WHERE customer_id IS NULL;A count above zero explains the empty result. You can also compare against a NOT EXISTS version of the same query. If the two disagree, the cause is NULL handling.
Exercises
Exercise
The table orders has a column customer_id that contains the values 1, 1, and NULL. The customers with ids 2 and 3 have no orders. What does SELECT name FROM customers WHERE id NOT IN (SELECT customer_id FROM orders) return for customer 2, and why?
Show answer
It does not return customer 2, so the result is empty. The condition expands to 2 <> 1 AND 2 <> 1 AND 2 <> NULL. The last comparison is unknown, so the whole AND is unknown. WHERE keeps only rows whose condition is true, so customer 2 is dropped, along with every other customer that has no order.
Exercise
Rewrite SELECT name FROM employees WHERE id NOT IN (SELECT manager_id FROM employees) so it correctly returns employees who manage nobody. Assume manager_id is NULL for the top executive.
Show answer
Use NOT EXISTS: SELECT e.name FROM employees e WHERE NOT EXISTS (SELECT 1 FROM employees m WHERE m.manager_id = e.id);. Alternatively, keep NOT IN and add WHERE manager_id IS NOT NULL inside the subquery. The original fails because the top executive's NULL manager_id makes NOT IN unknown for every employee who is not a manager.
Exercise
A subquery returns no rows at all. What does x NOT IN (subquery) evaluate to, and does it matter whether x is NULL?
Show answer
It evaluates to true for every outer row, and it does not matter whether x is NULL. An empty list contains no comparisons that could be false or unknown, so the negated membership test is true.