Sub topic 13
NOT EXISTS and NOT IN as Alternatives
This chapter assumes you can write a LEFT JOIN, know that a LEFT JOIN with WHERE ... IS NULL finds unmatched rows, and understand that comparing anything to NULL gives "unknown" rather than true or false. It uses the same customers and orders tables as the earlier chapters. Cleo has no orders, and order 104 has a NULL customer_id.
Three ways to ask the same question
"Which customers have never placed an order?" can be written three ways. The first is the LEFT JOIN anti-join you already know:
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
-- CleoThe second uses NOT EXISTS:
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id
);
-- CleoThe third uses NOT IN:
SELECT c.name
FROM customers c
WHERE c.customer_id NOT IN (
SELECT o.customer_id FROM orders o
);
-- (no rows)The third query returns nothing, even though Cleo has no orders. The reason is the most common bug in this area, and the rest of the chapter explains it and how to avoid it.
How NOT EXISTS works
EXISTS is a test on a subquery. It is true if the subquery returns at least one row and false if it returns none. NOT EXISTS reverses that.
The subquery here is correlated. It refers to c.customer_id from the outer query, so conceptually the database runs it once for each customer. For Ada it finds orders, so EXISTS is true and NOT EXISTS is false. For Cleo it finds none, so NOT EXISTS is true and her row is kept.
Three details are worth knowing:
- The select list inside
EXISTSis irrelevant.SELECT 1,SELECT *andSELECT o.order_idall behave the same, because only the presence of rows matters.SELECT 1is a convention that signals this. EXISTSnever returns "unknown". The subquery either has a row or it does not, so NULLs in the data cannot make the test unknown.- Each outer row is tested once. A customer with 500 orders still produces at most one output row, so
NOT EXISTSnever multiplies rows.
In practice, database optimizers usually turn a correlated NOT EXISTS into an anti-join, the same plan they use for the LEFT JOIN form. Do not assume the correlated subquery runs row by row on a real engine.
Why NOT IN returns nothing
x NOT IN (a, b, c) is shorthand for NOT (x = a OR x = b OR x = c). The orders.customer_id column contains a NULL (order 104), so the list the subquery produces is 1, 1, 2, NULL. For Cleo (id 3):
3 NOT IN (1, 1, 2, NULL)
= NOT (3 = 1 OR 3 = 1 OR 3 = 2 OR 3 = NULL)
= NOT (false OR false OR false OR unknown)
= NOT (unknown)
= unknownWHERE keeps only rows where the condition is true. An unknown result is dropped, so Cleo is dropped. The same happens for every customer, because no customer id ever equals NULL. A single NULL anywhere in the subquery's results makes NOT IN return no rows for any value that is not found in the list.
You can see this with literals:
SELECT 3 NOT IN (1, 2) AS without_null, -- true
3 NOT IN (1, 2, NULL) AS with_null; -- NULL (unknown)Fixing NOT IN
There are two fixes. The first is to filter the NULLs out of the subquery:
SELECT c.name
FROM customers c
WHERE c.customer_id NOT IN (
SELECT o.customer_id
FROM orders o
WHERE o.customer_id IS NOT NULL
);
-- CleoThe second is to use NOT EXISTS, which has no such problem. A third protection is to declare the column NOT NULL where the business rules allow it. In this schema the NULL is a real case, an order with no customer, so the constraint would be wrong here.
NOT IN is also safe with a literal list that contains no NULLs, for example WHERE status NOT IN ('cancelled', 'refunded'). The risk comes from subqueries and from lists built from nullable columns or parameters.
There is a related gotcha on the other side. If the value being tested is NULL, NOT IN is unknown as well, because NULL = anything is unknown. In the next section, order 104 cannot be found with NOT IN for that reason.
Anti-joins in the other direction
To find orders whose customer does not exist (or is missing), reverse the roles:
SELECT o.order_id, o.total
FROM orders o
WHERE NOT EXISTS (
SELECT 1 FROM customers c WHERE c.customer_id = o.customer_id
);
-- 104 15.00For order 104, c.customer_id = NULL is never true, so the subquery returns no rows and NOT EXISTS is true. The row is kept. This is usually what you want for finding orphans.
The NOT IN version looks equivalent, but it is not:
SELECT o.order_id, o.total
FROM orders o
WHERE o.customer_id NOT IN (
SELECT c.customer_id FROM customers c
);
-- (no rows)Here the subquery has no NULLs (the primary key forbids them), but the tested value o.customer_id is NULL for order 104, so NULL NOT IN (1, 2, 3) is unknown and the row is dropped. NOT EXISTS and the LEFT JOIN anti-join both return order 104. NOT IN does not.
Anti-joins with extra conditions
Real questions often add a condition: "customers with no order over 40". Each form handles it differently, and mistakes here usually involve the ON versus WHERE distinction from earlier in the tutorial.
-- NOT EXISTS: the extra condition goes inside the subquery
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
AND o.total > 40
);
-- Ben
-- Cleo-- LEFT JOIN: the extra condition goes in ON, never in WHERE
SELECT c.name
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id AND o.total > 40
WHERE o.order_id IS NULL;
-- Ben
-- CleoAda is excluded because order 101 is 50.00. Ben has an order, but it is only 35.00, so he has no qualifying order and is returned. If you moved o.total > 40 into the WHERE clause of the LEFT JOIN form, the query would require both o.order_id IS NULL and o.total > 40. A NULL-padded row has total NULL, so the condition is never true and the result is empty.
With NOT IN, the condition goes in the subquery's WHERE clause, and the NULL rule still applies:
SELECT c.name
FROM customers c
WHERE c.customer_id NOT IN (
SELECT o.customer_id
FROM orders o
WHERE o.total > 40
AND o.customer_id IS NOT NULL
);
-- Ben
-- CleoIn this particular data the subquery would be safe without the NULL filter, because order 104 has a total of 15.00 and is filtered out by total > 40. Keep the filter anyway, because the data will change.
Comparing the three approaches
| Aspect | LEFT JOIN ... IS NULL | NOT EXISTS | NOT IN |
|---|---|---|---|
| NULLs in the right table's key | Safe | Safe | Returns no rows |
| NULL in the tested value | Handled as no match | Handled as no match | Row is dropped |
| Intent is clear to a reader | Moderate; needs the `IS NULL` convention | High | High |
| Extra match conditions | In the `ON` clause | In the subquery `WHERE` | In the subquery `WHERE` |
| Can return columns from the right table | Yes (all NULL for unmatched rows) | No | No |
| Risk of duplicate rows | None for the anti-join form | None | None |
Some practical guidance:
- Default to
NOT EXISTSfor "rows with no match". It is correct with NULLs, and the query says what it means. - Use the LEFT JOIN form when you are already joining the table for other columns, or when your team prefers it. Test a column that cannot be NULL in a matched row, such as the primary key
o.order_id. Testing a nullable column likeo.totalwould wrongly treat matched rows with a NULL total as unmatched. - Use
NOT INfor short literal lists. For subqueries, use it only when the subquery column is declaredNOT NULLor you filter NULLs out explicitly.
On performance, modern PostgreSQL, MySQL, SQL Server and Oracle all generally plan NOT EXISTS and the LEFT JOIN anti-join efficiently, often identically. NOT IN is the one most likely to get a slower plan, partly because the engine must preserve the NULL semantics. Do not choose by guesswork. Check the plan with EXPLAIN on your own data and indexes, and make sure orders.customer_id is indexed, since all three forms search that column.
Common errors
- Using
NOT INwith a nullable subquery column. The query returns no rows. AddIS NOT NULLinside the subquery or switch toNOT EXISTS. - Forgetting the correlation in
NOT EXISTS. If you writeSELECT 1 FROM orderswith no link toc, the subquery returns rows for every customer as soon as any order exists.NOT EXISTSis then false for all customers, and the result is empty. - Putting the extra condition in
WHEREof an anti-join. It cancels the NULL-padded rows you are looking for. Put it inON. - Testing the wrong column for NULL. Use a right-table column that is
NOT NULL, usually its primary key. - Writing
NOT IN (SELECT ... )when the subquery can be empty. An empty list makesNOT INtrue for every row, including rows where the tested value is NULL. This is correct logically but surprising, so check the result when the subquery's filter is selective.
Exercise
The query below is meant to list orders whose customer is not in customers, but it returns no rows even though order 104 has no customer. Explain why, and rewrite it so it returns order 104.
SELECT o.orderid
FROM orders o
WHERE o.customerid NOT IN (SELECT c.customer_id FROM customers c);
Show answer
For order 104, o.customer_id is NULL, so NULL NOT IN (1, 2, 3) evaluates to unknown, and WHERE discards unknown rows. The other orders have customers that are in the list, so they are excluded as well. Rewrite with NOT EXISTS:
SELECT o.orderid
FROM orders o
WHERE NOT EXISTS (
SELECT 1 FROM customers c WHERE c.customerid = o.customer_id
);
This returns order 104, because no customer row equals NULL, so the subquery is empty for that order.
Exercise
Write a query that lists customers who have no order with a total of 30.00 or more, using the LEFT JOIN anti-join form. Say which customers it returns for the sample data and why.
Show answer
SELECT c.name
FROM customers c
LEFT JOIN orders o
ON o.customerid = c.customerid AND o.total >= 30
WHERE o.order_id IS NULL;
It returns Cleo only. Ada has order 101 at 50.00 and Ben has order 103 at 35.00, so both have a qualifying order and are matched. Cleo has no orders, so she stays NULL-padded. The total >= 30 condition must be in ON. In WHERE it would remove the NULL-padded rows and return nothing.
Exercise
A teammate fixes the NOT IN bug by adding WHERE o.total IS NOT NULL to the subquery. Does this fix it? What should the filter be?
Show answer
No. total is declared NOT NULL, so that filter removes nothing, and the NULL in o.customer_id (order 104) is still in the list, so the outer query still returns no rows. The filter must be on the column that appears in the list: WHERE o.customer_id IS NOT NULL. Using NOT EXISTS avoids the problem entirely.