Sub topic 7
EXISTS and NOT EXISTS
This chapter assumes you can write correlated subqueries, understand NULL and three-valued logic, and know the difference between INNER JOIN and LEFT JOIN. Earlier chapters showed that NOT IN can fail silently when the subquery returns a NULL. EXISTS and NOT EXISTS avoid that problem. They also express "does a related row exist?" more directly than most other forms.
What EXISTS tests
EXISTS takes a subquery and returns a Boolean. It is true if the subquery returns at least one row and false if it returns none. It does not compare values. It does not care what the subquery returns, only whether any row comes back.
SELECT c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
);This returns customers who have placed at least one order. The subquery is correlated: it refers to c.id from the outer query. Conceptually, the database takes each customer row, runs the subquery with that customer's id, and keeps the customer if any order row comes back.
"Conceptually" matters here. The database is free to execute the query in a different way, as long as the result is the same. Most optimizers turn EXISTS into a semi-join, which stops searching for a customer's orders as soon as it finds the first match.
flowchart TDThe diagram below shows the evaluation model.
The SELECT list inside EXISTS does not matter
The subquery's select list is ignored. These three forms behave identically:
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
WHERE EXISTS (SELECT * FROM orders o WHERE o.customer_id = c.id)
WHERE EXISTS (SELECT NULL FROM orders o WHERE o.customer_id = c.id)SELECT 1 is the common convention because it signals that no column values are used. SELECT * is also safe. The database does not expand the columns or read them. Even SELECT NULL works, because EXISTS counts rows and does not inspect their values.
The rows themselves are what count. The WHERE clause inside the subquery decides whether a row exists. If you forget the correlation condition, the subquery no longer depends on the outer row:
-- Bug: the subquery is not correlated
SELECT c.name
FROM customers c
WHERE EXISTS (SELECT 1 FROM orders o);This returns every customer if the orders table has any rows at all, and no customers if it is empty. The missing o.customer_id = c.id is a common cause of an EXISTS query that returns far too many rows.
NOT EXISTS: finding rows with no match
NOT EXISTS is true when the subquery returns no rows. It is the standard way to answer "which customers have no orders?"
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
);This query is not affected by NULL values in orders.customer_id. Here is why. An order row whose customer_id is NULL fails the test o.customer_id = c.id. The comparison evaluates to unknown, and a WHERE clause only keeps rows where the condition is true. So that order is never counted as a match for any customer, and the subquery's result for each customer depends only on the orders that really belong to them.
Compare the NOT IN version:
SELECT c.name
FROM customers c
WHERE c.id NOT IN (SELECT o.customer_id FROM orders o);If orders.customer_id contains even one NULL, then for every customer c.id NOT IN (...) evaluates to unknown rather than true, and the query returns no rows. NOT EXISTS has no such failure mode.
EXISTS versus IN
For a simple membership test, IN and EXISTS give the same result when no NULLs are involved:
-- With IN
SELECT name
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE total > 100);
-- With EXISTS
SELECT c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
AND o.total > 100
);The differences are:
| Aspect | IN | EXISTS |
|---|---|---|
| Compares values | Yes, outer value against a list | No, only tests whether any row exists |
| Correlation | Usually not correlated | Usually correlated |
| Multi-column match | Awkward and not portable | Easy: add more conditions in the subquery |
| NULL in subquery | Matters for NOT IN | No effect on NOT EXISTS |
| Reads as | "is this value in the set?" | "is there a matching row?" |
Modern optimizers in PostgreSQL, MySQL 8, SQL Server, and Oracle usually produce the same plan for IN and EXISTS. Choose by correctness and readability first. The NULL behavior of the negated forms is the real reason to choose one over the other.
Multiple conditions and extra tables
Because EXISTS only needs a row to exist, the subquery can match on several columns or join other tables. This is where it is clearer than IN.
SELECT c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
JOIN order_items i ON i.order_id = o.id
WHERE o.customer_id = c.id
AND i.quantity >= 10
);This finds customers with at least one order containing a line item of 10 or more units. Writing the same thing with an inner join would repeat a customer once for every qualifying order line, so you would need DISTINCT to remove the duplicates. EXISTS returns each customer at most once, because it is a test on the customer row and does not multiply rows.
Combining EXISTS and NOT EXISTS
You can use both in one query. For example, customers who have orders but no unpaid ones:
SELECT c.name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.id
)
AND NOT EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.id
AND o.status = 'unpaid'
);This pattern is called a "relational division" in a limited form: all of a customer's orders must satisfy a condition. SQL has no "for all" operator, so you write it as "there exists no row that violates the condition." The first EXISTS guards against customers with no orders at all, since NOT EXISTS alone would also return them.
EXISTS versus a LEFT JOIN anti-join
Another way to find unmatched rows is a LEFT JOIN followed by a test for NULL:
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
WHERE o.id IS NULL;This returns the same customers as the NOT EXISTS version. Check o.id, the primary key of orders, because a primary key is never NULL in a real matching row. Testing a nullable column can give wrong results, since a matched row might have NULL in it too.
Both forms are correct. Most optimizers treat them as an anti-join. NOT EXISTS states the intent more clearly, and it cannot accidentally multiply rows, while the join form is sometimes familiar to people who learn joins first. The next chapters on subqueries versus joins return to this choice.
Common errors
- Missing correlation. The subquery has no link to the outer row, so
EXISTSis true or false for every row at once. - Wrong alias in the correlation. In
WHERE o.customer_id = o.id, both sides refer to the same table. Use distinct, meaningful aliases. - Using NOT IN on a nullable column. Switch to
NOT EXISTS. - Putting the condition in the wrong place. In the "no unpaid orders" example, the test
o.status = 'unpaid'belongs inside the subquery. If you put it in the outerWHERE, you filter on outer columns instead. - Expecting EXISTS to return data. It returns only true or false. If you need values from the related rows, use a join.
Checking your understanding
Exercise
A table products(id, name) and a table reviews(id, product_id, rating) are given. reviews.product_id is nullable. Write a query that returns the names of products that have no reviews, in a form that still works if some reviews have a NULL product_id.
Show answer
Use NOT EXISTS: SELECT p.name FROM products p WHERE NOT EXISTS ( SELECT 1 FROM reviews r WHERE r.productid = p.id ); A review with a NULL productid fails the comparison r.product_id = p.id, so it is never counted as a match. The NOT IN form would return no rows at all if any NULL were present.
Exercise
Using the same tables, write a query that returns products that have at least one review and where no review has a rating below 3.
Show answer
Combine EXISTS and NOT EXISTS: SELECT p.name FROM products p WHERE EXISTS ( SELECT 1 FROM reviews r WHERE r.productid = p.id ) AND NOT EXISTS ( SELECT 1 FROM reviews r WHERE r.productid = p.id AND r.rating < 3 ); The EXISTS part excludes products with no reviews. Without it, such products would pass the NOT EXISTS test and appear in the result.
Exercise
What does this query return, and why is it probably a mistake? SELECT c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o);
Show answer
It returns every customer if the orders table has at least one row, and no customers if it is empty. The subquery has no condition linking it to c, so its result is the same for every customer. The intended query needs WHERE o.customer_id = c.id inside the subquery.