IntermediateNULL handling

Why does NOT IN return no rows when the subquery contains a NULL? What should you use instead?

Scenario

You need customers who have never placed an order. One order row has a NULL customer_id, and the NOT IN query suddenly returns nothing.

Interview answerTry answering first, then reveal

x NOT IN (1, 2, NULL) means x <> 1 AND x <> 2 AND x <> NULL. The last comparison is UNKNOWN, so the whole condition is never TRUE and no rows pass. Use NOT EXISTS (or a LEFT JOIN ... WHERE right.key IS NULL), which is NULL-safe.

Explanation

SQL has three-valued logic: TRUE, FALSE and UNKNOWN. Any comparison with NULL is UNKNOWN, and WHERE keeps only rows where the condition is TRUE.

TRUE AND UNKNOWN is UNKNOWN, so one NULL in the list makes every NOT IN check UNKNOWN. IN does not have the problem because TRUE OR UNKNOWN is TRUE.

NOT EXISTS asks "is there a matching row?", which is always TRUE or FALSE, so NULLs in the subquery cannot poison it.

Worked example

Run on DuckDB when this page was built; the results shown are the real output.

Sample data
SQL
CREATE TABLE customers (customer_id INT, name VARCHAR);
CREATE TABLE orders (order_id INT, customer_id INT);
INSERT INTO customers VALUES (1, 'Asha'), (2, 'Ben'), (3, 'Chen');
INSERT INTO orders VALUES (100, 1), (101, 1), (102, NULL);

Three ways to find customers with no orders

SQL
SELECT 'NOT IN' AS method, COUNT(*) AS customers_found
FROM customers WHERE customer_id NOT IN (SELECT customer_id FROM orders)
UNION ALL
SELECT 'NOT EXISTS', COUNT(*)
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)
UNION ALL
SELECT 'LEFT JOIN / IS NULL', COUNT(*)
FROM customers c LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
Result
methodcustomers_found
NOT IN0
NOT EXISTS2
LEFT JOIN / IS NULL2

Ben and Chen have no orders, so the right answer is 2. NOT IN finds 0.

In production

  • Prefer NOT EXISTS for anti joins by default. Optimisers turn it into an efficient anti join in PostgreSQL, SQL Server, Oracle and Spark.
  • If you must use NOT IN, filter the subquery: WHERE customer_id IS NOT NULL.
  • Declare join keys NOT NULL where the business allows it. The constraint documents the data and removes the trap.

Common mistakes

  • Testing only on clean sample data and shipping a query that breaks the first time a NULL arrives.
  • Writing WHERE col = NULL instead of WHERE col IS NULL.
  • In the LEFT JOIN version, testing a nullable column of the right table instead of its key.

More on this topic in the SQL Interview Questions guide, or browse all SQL questions.