Sub topic 9
The NOT IN Trap and the NOT EXISTS Fix
This chapter assumes you know basic SELECT, WHERE, JOIN, and subqueries, and that you have seen three-valued logic (TRUE, FALSE, UNKNOWN) and the rule that WHERE keeps only rows whose condition is TRUE. The examples use the employees table below. Ada has no manager, and Ada and Cy have no commission.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL,
manager_id INTEGER,
commission NUMERIC(8,2)
);
INSERT INTO employees (id, name, manager_id, commission) VALUES
(1, 'Ada', NULL, NULL),
(2, 'Ben', 1, 100.00),
(3, 'Cy', 1, NULL),
(4, 'Di', 2, 300.00);The Query That Returns Nothing
Suppose you want the employees who manage nobody. "Not in the list of managers" reads naturally as NOT IN:
SELECT name FROM employees
WHERE id NOT IN (SELECT manager_id FROM employees);You expect Cy and Di. The query returns no rows, and it raises no error or warning. An empty result looks like a valid answer ("everyone manages someone"), so this bug often goes unnoticed.
The cause is the NULL in Ada's manager_id. The subquery returns the values 1, 1, 2 and NULL.
Why NOT IN Fails
x IN (a, b, c) is shorthand for x = a OR x = b OR x = c. x NOT IN (a, b, c) is the negation of that, which is equivalent to x <> a AND x <> b AND x <> c.
Now expand the test for Cy (id 3) against the list 1, 1, 2, NULL:
3 <> 1 TRUE
3 <> 1 TRUE
3 <> 2 TRUE
3 <> NULL UNKNOWNCombining these with AND gives TRUE AND TRUE AND TRUE AND UNKNOWN, which is UNKNOWN. WHERE discards rows whose condition is UNKNOWN, so Cy is dropped. The same happens for Di and for every other row.
The NULL poisons the whole test, and it does so only on the NOT IN side:
| Expression | Result |
|---|---|
| `3 IN (1, 2, NULL)` | UNKNOWN |
| `2 IN (1, 2, NULL)` | TRUE |
| `3 NOT IN (1, 2, NULL)` | UNKNOWN |
| `2 NOT IN (1, 2, NULL)` | FALSE |
| `3 NOT IN (1, 2)` | TRUE |
A positive IN still works when a match exists, because TRUE OR UNKNOWN is TRUE. NOT IN can only return TRUE if every comparison is TRUE, and a NULL comparison can never be TRUE. So once the list contains one NULL, NOT IN returns either FALSE or UNKNOWN for every row. It never returns TRUE.
Fix 1: NOT EXISTS
NOT EXISTS tests whether a correlated subquery returns any row at all. It does not compare a value against a list, so a NULL in the subquery has no effect on the outcome:
SELECT e.name FROM employees e
WHERE NOT EXISTS (
SELECT 1 FROM employees m WHERE m.manager_id = e.id
);This returns Cy and Di. For Ada, the subquery finds Ben and Cy (their manager_id equals 1), so EXISTS is TRUE and NOT EXISTS is FALSE. For Cy, the subquery compares m.manager_id = 3. That is FALSE for the three non-NULL rows and UNKNOWN for Ada's row. No row has a TRUE condition, so the subquery is empty, and NOT EXISTS is TRUE.
The key difference is that EXISTS and NOT EXISTS always yield TRUE or FALSE. They never yield UNKNOWN. The UNKNOWN produced inside the subquery's WHERE only causes that inner row to be skipped.
Fix 2: Filter the NULLs Out of the Subquery
If you prefer to keep NOT IN, remove the NULLs from the list explicitly:
SELECT name FROM employees
WHERE id NOT IN (
SELECT manager_id FROM employees WHERE manager_id IS NOT NULL
);This returns Cy and Di. It is correct, but it depends on you remembering the filter. If someone later rewrites the subquery and drops the IS NOT NULL, the query silently breaks again.
Fix 3: LEFT JOIN Anti-Join
An anti-join keeps rows from one table that have no match in another. You write it as a LEFT JOIN and then keep the rows where the join found nothing:
SELECT e.name
FROM employees e
LEFT JOIN employees m ON m.manager_id = e.id
WHERE m.id IS NULL;When no row matches, the database fills the columns of m with NULLs. Testing m.id IS NULL works because id is a primary key, so it is never NULL in a matched row. Do not test a nullable column such as m.manager_id or m.commission, because a matched row could also have NULL there and be mistaken for "no match".
Choosing Between the Three
| Approach | Safe with NULLs in the subquery | Notes |
|---|---|---|
| `NOT IN` | No | Correct only if the subquery column can never be NULL, or you filter it. |
| `NOT EXISTS` | Yes | Clear intent, works with multi-column keys, usually the best default. |
| `LEFT JOIN ... IS NULL` | Yes | Familiar to many people, but easy to get wrong by testing the wrong column. |
Most modern optimizers (PostgreSQL, SQL Server, Oracle, MySQL 8) turn NOT EXISTS and the LEFT JOIN form into the same anti-join plan, so performance is usually similar. NOT IN is different. Because it must account for NULLs, some systems cannot use an anti-join plan for it unless they can prove the column is NOT NULL. In PostgreSQL, for example, a NOT IN subquery is often executed as a hashed subplan or repeated scan, and it can be much slower on large tables. Check the execution plan on your own system rather than relying on a rule of thumb.
Edge Cases
A literal list with a NULL
The same trap applies when you write the list by hand or pass it as a parameter:
-- Returns no rows, whatever is in employees.
SELECT name FROM employees WHERE id NOT IN (1, 2, NULL);This often appears when an application builds the list from a collection that contains a missing value.
An empty list or empty subquery
If the subquery returns no rows at all, NOT IN is TRUE for every row, including rows where the tested value is NULL. This is the one case where the left side being NULL does not matter. With a non-empty list, a NULL on the left side gives UNKNOWN:
-- Returns no rows: NULL NOT IN (1, 2) is UNKNOWN.
SELECT 1 WHERE NULL NOT IN (1, 2);So NOT IN can fail from either side. A NULL in the list blocks every row, and a NULL on the left blocks that row.
NULL on the left side with NOT EXISTS
NOT EXISTS also treats the left value correctly. If you compare m.manager_id = e.id and e.id were NULL, no inner row would match, and NOT EXISTS would return TRUE. Check that this is what you want. If a NULL key should mean "unknown, so exclude it", add an explicit e.id IS NOT NULL condition.
NOT IN with a column that has a NOT NULL constraint
If the subquery column is declared NOT NULL, NOT IN is safe today. The risk is that constraints can change. A later migration that relaxes the constraint will break the query without any error. Using NOT EXISTS removes that dependency.
Using NOT IN on a join key from an outer join
A subquery that selects from the right side of an outer join can produce NULLs even if the underlying column is NOT NULL, because unmatched rows are padded with NULL. Watch for this when the subquery contains a LEFT JOIN.
A Checklist for Reviewing NOT IN
- Does the subquery column allow NULL, now or after a future change?
- Can the subquery produce NULLs through an outer join, an expression, or a function such as NULLIF?
- Can the value on the left side be NULL?
- Is the list built from parameters that might contain NULL?
If any answer is yes or "not sure", switch to NOT EXISTS.
Exercise
A table orders(id, customer_id) and a table customers(id) are given. Some rows in orders have a NULL customer_id (guest checkouts). You want the customers who have placed no orders. Explain why SELECT id FROM customers WHERE id NOT IN (SELECT customer_id FROM orders) returns no rows, and write a corrected query using NOT EXISTS.
Show answer
The subquery returns a NULL for the guest orders. For each customer, id <> NULL is UNKNOWN, so the AND of all the comparisons can never be TRUE, and WHERE discards every row. The corrected query is: SELECT c.id FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
Exercise
What does SELECT 1 WHERE 5 NOT IN (SELECT manager_id FROM employees WHERE id = 99) return when no employee has id 99, and why?
Show answer
It returns one row. The subquery is empty, so NOT IN is TRUE for any left value, because there are no comparisons that could be UNKNOWN. The NULL problem only appears when the list is non-empty and contains a NULL.