Sub topic 5
NOT EXISTS: finding rows with no match
This chapter assumes you can write SELECT and WHERE queries, use INNER JOIN and LEFT JOIN, and read table aliases. It also assumes you know that NULL means a missing value, and you have seen the correlated subquery and EXISTS from the earlier chapters. Here you will use NOT EXISTS to answer "which rows have nothing related to them?"
The question NOT EXISTS answers
Many business questions are about absence:
- Which customers have never placed an order?
- Which products were not sold last month?
- Which employees have no assigned manager?
EXISTS tests whether a correlated subquery returns at least one row. NOT EXISTS is the opposite. It is true only when the subquery returns no rows at all for the current outer row.
The examples in this chapter use these tables. Run the script if you want to follow along. It uses standard SQL, and the date literals work in PostgreSQL, MySQL, and SQLite.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
order_date DATE NOT NULL,
total DECIMAL(10,2) NOT NULL,
status VARCHAR(20) NOT NULL
);
INSERT INTO customers (customer_id, name) VALUES
(1, 'Ada'), (2, 'Ben'), (3, 'Cleo'), (4, 'Dev');
INSERT INTO orders (order_id, customer_id, order_date, total, status) VALUES
(101, 1, '2026-01-15', 120.00, 'shipped'),
(102, 1, '2026-03-02', 80.00, 'cancelled'),
(103, 2, '2025-06-20', 45.00, 'shipped'),
(104, 3, '2026-05-10', 300.00, 'pending'),
(105, NULL, '2026-02-01', 20.00, 'shipped');Order 105 has no customer. It is deliberate, because it lets us check how NOT EXISTS behaves when the inner table contains a NULL in the correlation column.
The basic pattern
To find customers with no orders:
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);The result is one row: Dev (customer 4).
The database reads this as follows. For each customer row, run the inner query with that customer's customer_id. If the inner query finds any order, EXISTS would be true, so NOT EXISTS is false and the customer is dropped. If it finds none, NOT EXISTS is true and the customer stays.
The result is only ever true or false
EXISTS and NOT EXISTS never produce UNKNOWN. A subquery either returns at least one row or it returns none. The values inside the rows are not examined. This is why NOT EXISTS is safer than NOT IN when NULL can appear, which a later chapter covers in detail.
You can check this with the sample data. Order 105 has a NULL customer_id. The comparison o.customer_id = c.customer_id is UNKNOWN for that order, and WHERE treats UNKNOWN like false. Order 105 therefore never matches any customer, and the query still correctly returns Dev.
Putting the condition inside the subquery
Absence is usually about a specific kind of related row. For example, "no orders in 2026" is different from "no orders at all." The extra condition belongs inside the subquery, next to the correlation condition:
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
AND o.order_date >= '2026-01-01'
);This returns Ben (his only order is from 2025) and Dev (no orders). Ada and Cleo each have a 2026 order, so they are excluded.
Read the inner WHERE as the definition of what counts as a match. The outer NOT EXISTS then says "there is no such match." Cancelled orders count as matches in the query above. If cancelled orders should be ignored, add AND o.status <> 'cancelled' to the inner query.
Combining EXISTS and NOT EXISTS
You can use both in one query to express "has some, but none of a given kind." This finds customers who have placed orders, but none of them have shipped:
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
)
AND NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
AND o.status = 'shipped'
);The result is Cleo, whose only order is pending. Dev is excluded by the first condition. Ada and Ben are excluded by the second, because each has a shipped order.
Both subqueries use the alias o. That is legal, because each alias is visible only inside its own subquery.
Common errors
Forgetting the correlation
Suppose you drop the link between inner and outer query:
SELECT c.customer_id, c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
);The inner query no longer mentions c, so it returns the same rows for every customer. The orders table has rows, so NOT EXISTS is false for every customer and the result is empty. If orders were empty, you would get all customers. An all-or-nothing result is the usual sign of a missing correlation condition.
Correlating on the wrong column
Writing o.order_id = c.customer_id is valid SQL and runs without error. It compares an order number to a customer number, so it matches by coincidence. The database cannot catch this, so check that the columns on both sides of the correlation are the matching key pair. This is normally a foreign key and the primary key it references.
Putting the filter in the wrong place
Conditions about the inner table must stay inside the subquery. A condition like o.order_date >= '2026-01-01' in the outer WHERE fails with an error, because o is not visible there. Outer conditions that are about the customer, such as c.name LIKE 'A%', belong in the outer WHERE. They can be combined with AND.
Treating NOT EXISTS as the opposite of "all rows match"
NOT EXISTS (... WHERE o.status = 'shipped') means "no shipped order exists." It does not mean "all orders are not shipped" in a way that includes customers with zero orders. Because zero orders also satisfies it, Dev is included. Add a positive EXISTS check, as in the earlier example, when you want to exclude customers with no orders.
NOT EXISTS and the LEFT JOIN anti-join
You can express the same "no match" idea with a LEFT JOIN. This is called an anti-join. The LEFT JOIN keeps every customer, and the WHERE keeps only those where the join found nothing:
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;This returns Dev. The test uses o.order_id, a column that can never be NULL in a real order row, so a NULL there means the join found no order.
The two forms are equivalent for this question. A later chapter compares them and their performance in more detail. For this chapter, the point that matters is where an extra condition goes.
With a LEFT JOIN, a condition on the inner table must go in the ON clause, not in the WHERE. Here is the "no orders in 2026" query written correctly:
SELECT c.customer_id, c.name
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id
AND o.order_date >= '2026-01-01'
WHERE o.order_id IS NULL;If you put o.order_date >= '2026-01-01' in the WHERE instead, the condition requires a real order date, while o.order_id IS NULL requires a missing order. No row can satisfy both, so the query returns nothing. NOT EXISTS avoids this trap because the filter always lives inside the subquery.
| Question | NOT EXISTS | LEFT JOIN anti-join |
|---|---|---|
| No related rows at all | Correlation condition only | `WHERE o.key IS NULL` |
| No related rows of a given kind | Add the condition inside the subquery | Add the condition to the `ON` clause |
| Where the extra condition can go wrong | Hard to misplace | Easy to misplace in `WHERE` |
| Duplicates from the join | Never, outer rows are not multiplied | Not for the `IS NULL` form, since no match means one row |
Edge cases
- Customers with a NULL key. If a customer row had
customer_idset toNULL, theno.customer_id = c.customer_idis never true. The subquery finds nothing, andNOT EXISTSkeeps that customer. In practice a primary key cannot beNULL, but the same applies to any nullable correlation column. - Orders with a NULL customer. As seen with order 105, these never match any outer row, and they do not break
NOT EXISTS. - Empty inner table. If
ordershas no rows,NOT EXISTSis true for every customer. - Empty outer table. There are no outer rows to test, so the result is empty.
- The SELECT list. Writing
SELECT 1,SELECT *, orSELECT o.order_idinsideNOT EXISTSgives the same result, because only the presence of rows matters.SELECT 1is a common convention that signals "I only care that a row exists."
When NOT EXISTS is a good choice
Use NOT EXISTS when:
- the question is "no related row of kind X," especially with extra conditions on the related table;
- the correlation column on the inner side might contain
NULL; - you want to avoid the filter-placement mistake that
LEFT JOINinvites.
Consider a different form when you only need a plain list of unmatched keys from a column that is guaranteed non-null. Even then, NOT EXISTS is a safe default. Most modern optimizers turn it into an efficient anti-join plan, and the next chapters cover how to check this.
Exercise
Using the sample tables, write a query that returns customers who have no cancelled order. Which customers does it return, and does it include Dev, who has no orders at all?
Show answer
SELECT c.customerid, c.name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customerid = c.customer_id AND o.status = 'cancelled'); It returns Ben, Cleo, and Dev. Ada is excluded because order 102 is cancelled. Dev is included because having no orders means there is no cancelled order either. To exclude Dev, add an EXISTS test for any order.
Exercise
A colleague writes this query to find customers with no pending order, and it returns no rows even though Dev, Ada, and Ben have none: SELECT c.customer_id, c.name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.status = 'pending'); What is wrong, and how do you fix it?
Show answer
The inner query has no correlation to c, so it finds order 104 for every customer, and NOT EXISTS is false for all of them. Add the link: WHERE o.customerid = c.customerid AND o.status = 'pending'. The fixed query returns Ada, Ben, and Dev.