Sub topic 8
The NOT IN trap when NULLs are present
This chapter assumes you can write basic SELECT and WHERE queries, use INNER JOIN and LEFT JOIN, and read table aliases. It also assumes you know that NULL means a missing value. You should have seen EXISTS and NOT EXISTS in the earlier chapters.
By the end you will be able to explain why NOT IN can return no rows at all, predict when that happens, and choose a safe alternative.
The symptom
Suppose you want customers who have never placed an order. A natural first query uses NOT IN:
SELECT c.customer_id, c.name
FROM customers c
WHERE c.customer_id NOT IN (
SELECT o.customer_id
FROM orders o
);On clean data this works. Then one day a row is added to orders with a NULL customer_id, perhaps a guest checkout. The query now returns zero rows, even though many customers still have no orders. There is no error and no warning. The result is simply empty.
The query did not break because of a bug in the database. It follows the SQL rules for NULL exactly. To see why, you need three-valued logic.
Three-valued logic in a WHERE clause
Most programming languages have two truth values. SQL has three: TRUE, FALSE, and UNKNOWN. Comparing anything to NULL gives UNKNOWN, not FALSE.
| Expression | Result |
|---|---|
| `5 = 5` | TRUE |
| `5 = 6` | FALSE |
| `5 = NULL` | UNKNOWN |
| `NULL = NULL` | UNKNOWN |
| `5 <> NULL` | UNKNOWN |
A WHERE clause keeps a row only when its condition is TRUE. Rows where the condition is FALSE or UNKNOWN are both discarded.
The operators AND, OR, and NOT follow these rules:
| Expression | Result |
|---|---|
| `TRUE AND UNKNOWN` | UNKNOWN |
| `FALSE AND UNKNOWN` | FALSE |
| `TRUE OR UNKNOWN` | TRUE |
| `FALSE OR UNKNOWN` | UNKNOWN |
| `NOT UNKNOWN` | UNKNOWN |
The last row matters most here. Negating UNKNOWN does not give TRUE. It stays UNKNOWN, and the row is still discarded.
How NOT IN expands
x NOT IN (a, b, c) is shorthand for NOT (x IN (a, b, c)). The IN part is a chain of OR comparisons, so the whole expression is equivalent to:
x <> a AND x <> b AND x <> cNow put a NULL in the list. Take x = 3 and the list (1, 2, NULL):
3 <> 1is TRUE.3 <> 2is TRUE.3 <> NULLis UNKNOWN.TRUE AND TRUE AND UNKNOWNis UNKNOWN.
The row is discarded. The same happens for every possible value of x. The best any row can do is UNKNOWN, because the NULL comparison is always UNKNOWN and AND never lets UNKNOWN become TRUE. So the query returns nothing.
Compare this with IN. For 3 IN (1, 2, NULL), the expansion is 3 = 1 OR 3 = 2 OR 3 = NULL, which is FALSE OR FALSE OR UNKNOWN, giving UNKNOWN. If the value is present, as in 1 IN (1, 2, NULL), then TRUE OR ... is TRUE. So IN still finds matches when NULLs are present. It only fails to say "no" with certainty. That asymmetry is why IN is usually safe and NOT IN is not.
A small reproducible example
You can run this to see the trap yourself. It uses a small schema and works in PostgreSQL, SQLite, and most other databases.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
total NUMERIC(10, 2)
);
INSERT INTO customers (customer_id, name) VALUES
(1, 'Ada'),
(2, 'Ben'),
(3, 'Cleo');
INSERT INTO orders (order_id, customer_id, total) VALUES
(100, 1, 25.00),
(101, 1, 40.00);
SELECT c.customer_id, c.name
FROM customers c
WHERE c.customer_id NOT IN (SELECT o.customer_id FROM orders o);The final query returns Ben and Cleo, which is correct. Now add the guest order:
INSERT INTO orders (order_id, customer_id, total) VALUES (102, NULL, 15.00);
SELECT c.customer_id, c.name
FROM customers c
WHERE c.customer_id NOT IN (SELECT o.customer_id FROM orders o);The same query now returns no rows. Ben and Cleo are still customers without orders, but the NULL in the subquery result makes every NOT IN test UNKNOWN.
The fix: NOT EXISTS
NOT EXISTS does not compare values with <>. It asks whether the correlated inner query finds any row, and the answer is only TRUE or FALSE. A NULL in orders.customer_id never matches c.customer_id through the = test, so that order row is simply not counted as a match for anyone.
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);With the guest order present, this still returns Ben and Cleo. The comparison o.customer_id = c.customer_id is UNKNOWN for the NULL row, so the inner WHERE rejects it. No inner row survives for Ben, so NOT EXISTS is TRUE.
Here are the two forms side by side, as they appear in the spine. The first returns nothing when orders.customer_id contains a NULL. The second does not.
SELECT c.customer_id, c.name
FROM customers c
WHERE c.customer_id NOT IN (
SELECT o.customer_id
FROM orders o
);
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);Other ways to avoid the trap
NOT EXISTS is the usual choice, but there are other safe options.
Filter NULLs out of the subquery
If you prefer to keep NOT IN, remove the NULLs in the subquery:
SELECT c.customer_id, c.name
FROM customers c
WHERE c.customer_id NOT IN (
SELECT o.customer_id
FROM orders o
WHERE o.customer_id IS NOT NULL
);This is correct, but it depends on every author remembering the filter. A later edit that drops the line brings the bug back.
Use a LEFT JOIN anti-join
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;This is also NULL-safe. Test a column that can never be NULL in a real row, such as the primary key o.order_id. If you test a nullable column, you may confuse a real row holding a NULL with a missing match.
Declare the column NOT NULL
If a guest order should never exist, enforce it:
ALTER TABLE orders ALTER COLUMN customer_id SET NOT NULL;This syntax is for PostgreSQL. Other databases differ, for example ALTER TABLE orders MODIFY customer_id INTEGER NOT NULL in MySQL. A constraint is the strongest fix, because it removes the NULL at its source. Some optimizers also use a NOT NULL constraint to treat NOT IN more efficiently.
Choosing between the options
| Approach | NULL-safe | Notes |
|---|---|---|
| `NOT IN (subquery)` | No | Safe only if the subquery column cannot be NULL. |
| `NOT IN` with `IS NOT NULL` filter | Yes | Easy to forget in later edits. |
| `NOT EXISTS` | Yes | Reads as "there is no matching row". Usually the best default. |
| `LEFT JOIN ... IS NULL` | Yes | Test a non-nullable column of the joined table. |
Edge cases
A list of literals
The trap also applies to literal lists. WHERE status NOT IN ('new', 'open', NULL) matches no rows. This often happens when a list is built by application code from values that may be missing.
The outer value can be NULL too
Suppose a customer has customer_id NULL, which is unlikely for a primary key but possible for other columns. Then NULL NOT IN (subquery) is UNKNOWN whenever the subquery returns at least one row, so that row is excluded. With NOT EXISTS, the correlation test o.customer_id = NULL is UNKNOWN for every order, nothing matches, and the outer row is returned. The two forms can differ for NULL outer values, and neither is wrong. Decide which behavior you want.
An empty subquery result
If the subquery returns no rows, x NOT IN (empty set) is TRUE for every x, even when x is NULL. The trap only appears when the result contains at least one NULL.
Which column holds the NULL
Only a NULL in the subquery's selected column matters. A NULL elsewhere in the orders row, such as in total, has no effect on NOT IN (SELECT customer_id ...).
Detecting the problem early
When a NOT IN query returns fewer rows than expected, check the subquery for NULLs:
SELECT COUNT(*) AS null_rows
FROM orders o
WHERE o.customer_id IS NULL;A non-zero count means the trap is active. A good habit is to avoid NOT IN with subqueries in code that will be maintained over time, and to prefer NOT EXISTS from the start.
Exercises
Exercise
A table products has 50 rows. A query SELECT * FROM products WHERE product_id NOT IN (SELECT product_id FROM discontinued) returns 0 rows, although discontinued has only 3 rows and plenty of products are not on it. What is the most likely cause, and how would you confirm it?
Show answer
The discontinued.product_id column most likely contains at least one NULL. That makes product_id <> NULL UNKNOWN for every product, so the AND chain can never be TRUE. Confirm with SELECT COUNT(*) FROM discontinued WHERE product_id IS NULL;. Fix it with NOT EXISTS (SELECT 1 FROM discontinued d WHERE d.product_id = products.product_id), or add WHERE product_id IS NOT NULL to the subquery.
Exercise
Rewrite this query so it is safe when orders.customer_id can be NULL, using LEFT JOIN: SELECT c.name FROM customers c WHERE c.customer_id NOT IN (SELECT customer_id FROM orders).
Show answer
SELECT c.name FROM customers c LEFT JOIN orders o ON o.customer_id = c.customer_id WHERE o.order_id IS NULL; The test uses o.order_id, the primary key of orders, which is never NULL in a real row. A NULL there therefore means that no order matched.
Exercise
Evaluate 2 NOT IN (1, 3) and 2 NOT IN (1, 3, NULL) using the AND expansion. What does each give?
Show answer
2 NOT IN (1, 3) expands to 2 <> 1 AND 2 <> 3, which is TRUE AND TRUE, so TRUE. 2 NOT IN (1, 3, NULL) expands to 2 <> 1 AND 2 <> 3 AND 2 <> NULL, which is TRUE AND TRUE AND UNKNOWN, so UNKNOWN. A WHERE clause discards UNKNOWN, so the second case keeps no rows.