Sub topic 12
The NOT IN trap and other filter pitfalls
This chapter assumes you know three-valued logic (a comparison with NULL is unknown, not false), the IS NULL operator, and the HR sample tables employees and departments. It shows how NULL changes the results of WHERE clauses. The worst case is a NOT IN query that silently returns no rows.
How WHERE treats unknown
A WHERE clause keeps a row only when its condition evaluates to TRUE. Rows where the condition is FALSE or UNKNOWN are both discarded. The two cases look identical in the output, but they behave differently once you negate or combine conditions.
| 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. Negating an unknown condition does not turn it into TRUE, so NOT (x = y) does not return the rows that x = y skipped because of NULL.
The NOT IN trap
The two queries below differ only in the list.
SELECT 'row returned' AS msg FROM dual WHERE 1 NOT IN (2, 3);
SELECT 'row returned' AS msg FROM dual WHERE 1 NOT IN (2, NULL);The first query returns a row. The second returns none.
Oracle expands 1 NOT IN (2, NULL) into a chain of ANDed inequalities:
1 <> 2is TRUE.1 <> NULLis UNKNOWN.TRUE AND UNKNOWNis UNKNOWN, so the row is discarded.
A single NULL in the list makes the whole NOT IN unable to ever be TRUE. It can still be FALSE: 2 NOT IN (2, NULL) is FALSE, because 2 <> 2 is FALSE and FALSE AND UNKNOWN is FALSE. For any value that is not in the list, the answer is UNKNOWN.
Why plain IN does not have this problem
IN expands to ORed equalities. 1 IN (1, NULL) is TRUE OR UNKNOWN, which is TRUE. A value that is missing from the list gives UNKNOWN, which is discarded just as FALSE would be. The NULL in an IN list never changes which rows you get. This is why a query can work for months with IN and then break the day someone rewrites it with NOT IN.
The trap with a subquery
The trap rarely appears with a literal NULL. It usually appears when a subquery returns a nullable column. In the HR schema, employees.department_id is nullable, and one employee has no department. This query is meant to find departments with no employees:
SELECT d.department_name
FROM departments d
WHERE d.department_id NOT IN (SELECT e.department_id FROM employees e);The subquery returns one NULL, so the query returns no rows, even though several departments have no employees. Oracle raises no error and no warning.
Three ways to fix it
Filter the NULLs out of the subquery
SELECT d.department_name
FROM departments d
WHERE d.department_id NOT IN (SELECT e.department_id
FROM employees e
WHERE e.department_id IS NOT NULL);This keeps the NOT IN shape and states the intent clearly.
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);NOT EXISTS asks whether any matching row exists. A row with a NULL department_id never satisfies e.department_id = d.department_id, so it is simply not a match. NULLs cannot poison the result. This is usually the safest default for "rows with no match" questions.
Use NVL with a sentinel value
SELECT d.department_name
FROM departments d
WHERE d.department_id NOT IN (SELECT NVL(e.department_id, -1)
FROM employees e);This works only if the sentinel (-1) can never be a real value in the compared column. The sentinel also has to match the column's data type, as covered in the data type chapter. It is the weakest of the three options, because the assumption lives in your head and nowhere in the schema. Prefer IS NOT NULL or NOT EXISTS.
Inequality skips NULL rows
The same logic affects <>, !=, and NOT. Suppose you want every employee whose commission is not 0.2:
SELECT employee_id, commission_pct
FROM employees
WHERE commission_pct <> 0.2;Employees with a NULL commission are missing from the result. NULL <> 0.2 is UNKNOWN, so those rows are discarded. If "not 0.2" should include people with no commission, say so explicitly:
SELECT employee_id, commission_pct
FROM employees
WHERE commission_pct <> 0.2
OR commission_pct IS NULL;You can also write WHERE NVL(commission_pct, -1) <> 0.2. That has the same sentinel caveat as before, and it can interfere with index use (see below).
The rewrite NOT (commission_pct = 0.2) does not help. The inner comparison is UNKNOWN for NULL rows, and NOT UNKNOWN is still UNKNOWN.
Other filters that quietly drop NULL rows
Each of these treats NULL as "not a match", and none of them raise an error:
| Filter | What happens to NULL rows |
|---|---|
| `col = NULL` | Never TRUE for any row. Use `IS NULL`. |
| `col BETWEEN 1 AND 10` | NULL rows are dropped. |
| `col NOT BETWEEN 1 AND 10` | NULL rows are still dropped. |
| `col LIKE '%a%'` | NULL rows are dropped. |
| `col NOT LIKE '%a%'` | NULL rows are still dropped. |
| `col = ''` | Never TRUE, because Oracle treats `''` as NULL. Use `IS NULL`. |
The negated forms are where people go wrong. "Not between" and "not like" read as the complement of the positive filter. A NULL row appears in neither the filter nor its negation. Together, the two queries do not cover the whole table.
Optional parameters in filters
Search screens often have optional criteria. A common pattern is a bind variable that may be NULL, meaning "don't filter on this":
SELECT employee_id, department_id
FROM employees
WHERE (department_id = :dept OR :dept IS NULL);When :dept is NULL, the second branch is TRUE and every row passes, including rows whose department_id is NULL. When :dept has a value, only matching rows pass. This works because OR with a TRUE branch returns TRUE even when the other branch is UNKNOWN.
If you instead want a NULL parameter to mean "find rows where the column is NULL", you need an explicit test:
SELECT employee_id, department_id
FROM employees
WHERE department_id = :dept
OR (department_id IS NULL AND :dept IS NULL);Decide which meaning you want before you write the filter. A plain department_id = :dept with a NULL bind value returns nothing.
NVL in WHERE and index use
Wrapping a column in NVL inside a WHERE clause turns the column into an expression. A normal index on department_id generally cannot be used to evaluate NVL(department_id, -1) = 50, so Oracle may scan the whole table. Two ways around it:
- Rewrite the condition to compare the bare column, as in
department_id = 50, and addOR department_id IS NULLonly if you really need the NULL rows. - Create a function-based index on the same expression,
NVL(department_id, -1), if the wrapped form is the query you need to run often.
Also note that B-tree indexes on a single column do not store entries for rows where that column is NULL. A condition like department_id IS NULL cannot use such an index. It needs a composite index that includes a non-NULL column, or a function-based index.
A checklist for reviewing a filter
- List the nullable columns the condition touches.
- For each one, decide what should happen to NULL rows: kept, dropped, or treated as a default.
- If you use
NOT IN, confirm the list or subquery cannot contain NULL. Otherwise switch toNOT EXISTS. - If you use
<>,NOT LIKE, orNOT BETWEEN, addOR col IS NULLwhen NULL rows should be included. - Test with at least one row that has a NULL in each nullable column.
Exercise
A query SELECT * FROM orders WHERE customer_id NOT IN (SELECT customer_id FROM returns) returns no rows, even though many orders belong to customers who never made a return. Some rows in returns have a NULL customer_id. Explain why no rows come back, then write a corrected version that keeps the same meaning.
Show answer
The subquery returns at least one NULL. Each customer_id NOT IN (...) test expands into customer_id <> v1 AND customer_id <> v2 AND ... AND customer_id <> NULL. The last comparison is UNKNOWN, so the whole condition can be FALSE (when the customer appears in the list) or UNKNOWN (when it does not), but never TRUE. Every row is discarded. A corrected version is SELECT * FROM orders o WHERE NOT EXISTS (SELECT 1 FROM returns r WHERE r.customer_id = o.customer_id). Alternatively, keep NOT IN and add WHERE customer_id IS NOT NULL inside the subquery.
Exercise
Which rows does SELECT employee_id FROM employees WHERE commission_pct <> 0.2 omit, besides those with a commission of exactly 0.2? Rewrite the query so that those rows are included.
Show answer
It also omits rows where commission_pct is NULL, because NULL <> 0.2 is UNKNOWN and WHERE keeps only TRUE rows. The rewrite is WHERE commission_pct <> 0.2 OR commission_pct IS NULL.