Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 06 / Topic 3 of 8

The NOT IN trap

The most famous NULL bite in SQL. "Products from suppliers other than TechSource (supplier 1)":

SELECT name FROM products WHERE supplier_id NOT IN (1);
        name        
--------------------
 SQL for Beginners
 Postgres Deep Dive
 Chef Knife
 Coffee Maker
(4 rows)

Fine — but notice the Desk Lamp (NULL supplier) is already quietly missing. Now let a NULL into the list — say, from a subquery over a nullable column:

SELECT name FROM products WHERE supplier_id NOT IN (1, NULL);
 name 
------
(0 rows)

Zero rows. x NOT IN (1, NULL) means x <> 1 AND x <> NULL — and x <> NULL is unknown for every x, so no row can ever pass. A real query with NOT IN (SELECT ...) works for months, then the subquery's column gains one NULL and the report goes silently empty.

NOT EXISTS has no such failure mode — it tests row existence, not value equality:

SELECT p.name
FROM products AS p
WHERE NOT EXISTS (
  SELECT 1 FROM order_items AS oi WHERE oi.product_id = p.product_id
);
    name     
-------------
 USB-C Cable
(1 row)

Rule worth memorising whole: IN is fine; NOT IN against anything nullable is a bug waiting; write NOT EXISTS.

🧪 Quick quiz — answer from memory, then check.

  1. WHERE supplier_id NOT IN (1, NULL) returns…?
  2. Why is NOT EXISTS immune?
Show the answers
  1. No rows at all — x <> NULL is unknown, which poisons the whole AND chain.
  2. It checks "no matching row exists" instead of comparing values, so NULLs never enter the logic.

Exercise 3: Defuse the time bomb

What to do: "Customers with no events." First write it with NOT IN (SELECT customer_id FROM events) and confirm it works today. Then explain in one sentence why this query is a time bomb, and rewrite it so it never can be.

Sample output (both versions, today):

 first_name 
------------
 John
 Meera
 Sara
(3 rows)

💡 Hint: events.customer_id is nullable. One anonymous event — one NULL in that subquery — and NOT IN returns zero rows forever. NOT EXISTS doesn't care.


Show the solution to Exercise 3
-- Exercise 3: Defuse the time bomb
-- This works today only because no event row has a NULL customer_id:
SELECT first_name FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM events)
ORDER BY first_name;
-- events.customer_id is nullable. The day one anonymous event lands,
-- the query above returns zero rows with no error. The honest version:
SELECT c.first_name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM events e WHERE e.customer_id = c.customer_id)
ORDER BY c.first_name;

Search the guide