Sub topic 9
NULLs and the NOT IN trap
This chapter assumes you can write single-row and multi-row subqueries and use IN and EXISTS. It also assumes you know that NULL means "no known value" in SQL. The goal is to explain why NOT IN can silently return no rows, and how to write the query so it does not.
Three-valued logic in a WHERE clause
A comparison in SQL has three possible outcomes: true, false, or unknown. A comparison with NULL, such as 5 = NULL or NULL <> 3, is always unknown. A WHERE clause keeps a row only when its condition is true. Rows where the condition is false or unknown are both discarded.
| Expression | Result |
|---|---|
| `1 = 1` | true |
| `1 = 2` | false |
| `1 = NULL` | unknown |
| `NULL = NULL` | unknown |
| `1 <> NULL` | unknown |
| `true OR unknown` | true |
| `false OR unknown` | unknown |
| `true AND unknown` | unknown |
| `false AND unknown` | false |
| `NOT unknown` | unknown |
The last row of the table matters most here. Negating an unknown result does not make it true.
How IN and NOT IN are evaluated
Oracle treats x IN (a, b, c) as a chain of ORs:
x = a OR x = b OR x = cIt treats x NOT IN (a, b, c) as the negation, which is a chain of ANDs:
x <> a AND x <> b AND x <> cNow suppose c is NULL. In the IN form, a match on a or b still makes the whole OR true, so NULL in the set does no harm. In the NOT IN form, the term x <> NULL is unknown. An AND with an unknown term can be false, when another term is false, or unknown. It can never be true. Every row therefore fails the test.
You can see this without any tables:
SELECT 'row returned' AS result
FROM dual
WHERE 1 IN (1, NULL);
SELECT 'row returned' AS result
FROM dual
WHERE 1 NOT IN (2, NULL);The first query returns a row because 1 = 1 is true. The second returns no rows. The conditions 1 <> 2 (true) and 1 <> NULL (unknown) combine to unknown.
The trap in the HR schema
In the HR sample schema, the top-level employee (Steven King, employee 100) has a NULL manager_id. Suppose you want the employees who manage nobody:
SELECT last_name
FROM employees
WHERE employee_id NOT IN (SELECT manager_id FROM employees);The subquery returns every manager ID plus one NULL. For each employee, Oracle tests employee_id <> 100 AND employee_id <> 101 AND ... AND employee_id <> NULL. The last term is unknown for every row, so the query returns no rows. Oracle reports no error and no warning, so this is easy to miss. You get an empty result that looks plausible.
Fixing it
There are three common fixes.
Fix 1: filter NULLs out of the subquery
SELECT last_name
FROM employees
WHERE employee_id NOT IN (SELECT manager_id
FROM employees
WHERE manager_id IS NOT NULL);This works, but it relies on you remembering the filter. If the column later gains NULLs in a query where you forgot it, the bug returns.
Fix 2: use NOT EXISTS
SELECT e.last_name
FROM employees e
WHERE NOT EXISTS (SELECT 1
FROM employees r
WHERE r.manager_id = e.employee_id);EXISTS and NOT EXISTS never return unknown. They only ask whether the subquery returns at least one row. For an employee who manages nobody, the inner WHERE r.manager_id = e.employee_id is false or unknown for every row, so no row survives. NOT EXISTS is therefore true. A NULL manager_id in the inner table simply never matches, which is the behavior you want.
Fix 3: use an outer join anti-pattern
SELECT e.last_name
FROM employees e
LEFT JOIN employees r ON r.manager_id = e.employee_id
WHERE r.employee_id IS NULL;The left join keeps every employee. Employees with no subordinates get NULLs in the r columns. Testing a column that cannot be NULL in a real row, here the primary key r.employee_id, finds exactly those rows. This is correct for the same reason as NOT EXISTS: the join condition uses =, which never matches NULL.
Choosing a fix
| Technique | NULL-safe by itself | Notes |
|---|---|---|
| `NOT IN` plus `IS NOT NULL` filter | Only if you remember the filter | Short and readable, easy to get wrong later |
| `NOT EXISTS` | Yes | Usually the best default |
| `LEFT JOIN ... IS NULL` | Yes | Test a column that is never NULL in a real row |
| `NOT IN` with `NVL` | Fragile | You must pick a sentinel value that never occurs as real data |
Avoid NVL(manager_id, -1) style fixes. They work only while -1 is guaranteed not to be a real value, and they can stop the optimizer from using an index on manager_id.
Edge cases
NULL on the left-hand side
If the value being tested is NULL, the result is unknown even when the set has no NULLs:
SELECT 'row returned' AS result
FROM dual
WHERE NULL NOT IN (1, 2);This returns no rows. Employees with a NULL department_id (Kimberely Grant in the HR schema) are therefore dropped by a query such as WHERE department_id NOT IN (SELECT department_id FROM departments WHERE location_id = 1700). Whether you want those employees in the result is a business decision. If you do, NOT EXISTS keeps them, because the inner correlation never matches a NULL.
An empty subquery
If the subquery returns no rows, NOT IN is true for every outer row, even when the outer value is NULL. An empty set contains no NULL and no matching value, so there is nothing to make the test unknown.
IN is not affected
IN with a NULL in the set is safe for finding matches. The NULL never matches anything, and the other members still can. The trap is specific to negation.
Empty strings are NULL in Oracle
Oracle treats a zero-length character string as NULL. A VARCHAR2 column holding '' therefore contains NULLs. This is a common hidden source of the trap when the subquery reads a text column such as commission_code or an optional name field.
ALL and NULL
> ALL (subquery) follows the same AND logic as NOT IN. If the subquery returns a NULL, the comparison with that member is unknown, so the whole condition can never be true. The query from the earlier chapter that compares against department 30 stays safe only if salary has no NULLs in that department. Add AND salary IS NOT NULL to the subquery when the column is nullable.
Aggregates ignore NULLs
MAX(manager_id) and AVG(salary) skip NULLs, so a scalar subquery built on an aggregate does not hit this problem. If every input row is NULL, the aggregate itself returns NULL, and the outer comparison is unknown.
What the optimizer does with NOT IN
Oracle can run NOT IN as an anti join, which is fast on large tables. To keep NULL semantics, it needs either a NOT NULL constraint on the columns involved or a special null-aware anti join. Since Oracle Database 11g, the optimizer can use a null-aware anti join (shown as HASH JOIN ANTI NA in an execution plan), so NOT IN is not always slow. Declaring the column NOT NULL where the data allows it gives the optimizer the simplest plan, and it also prevents the bug at its source. NOT EXISTS is usually unnested to a regular anti join.
Checking for the problem
When a NOT IN query returns nothing and you expected rows, count the NULLs in the subquery column:
SELECT COUNT(*) AS null_managers
FROM employees
WHERE manager_id IS NULL;A count above zero explains the empty result.
Exercise
The query SELECT department_name FROM departments WHERE department_id NOT IN (SELECT department_id FROM employees) returns no rows, although the HR schema has departments with no employees. The employees table contains an employee whose department_id is NULL. Explain why, and rewrite the query so it returns departments with no employees.
Show answer
For every department, NOT IN expands to department_id <> d1 AND department_id <> d2 AND ... AND department_id <> NULL. The last term is unknown, so the whole condition can never be true and every row is rejected. Use NOT EXISTS: SELECT d.department_name FROM departments d WHERE NOT EXISTS (SELECT 1 FROM employees e WHERE e.department_id = d.department_id);. Adding WHERE department_id IS NOT NULL to the subquery also works.
Exercise
What does this query return, and why? SELECT 'yes' FROM dual WHERE 3 NOT IN (SELECT 1 FROM dual WHERE 1 = 0);
Show answer
It returns one row, yes. The subquery returns an empty set. With no members to compare against, and no NULL in the set, NOT IN is true, so the row is kept.
Exercise
A colleague fixes a NOT IN query by changing the subquery to SELECT NVL(manager_id, 0) FROM employees. Give one reason this is a weaker fix than NOT EXISTS.
Show answer
It depends on 0 never being a real employee ID, and wrapping the column in a function can prevent the optimizer from using an index on manager_id. NOT EXISTS needs no sentinel value and is NULL-safe by design.