Sub topic 3
EXISTS: asking whether any related row is there
This chapter assumes you can write SELECT and WHERE queries, use INNER JOIN and LEFT JOIN, give tables aliases, and treat NULL as a missing value. It also assumes you have seen a basic subquery in a WHERE clause. The previous chapter introduced correlated subqueries, where the inner query refers to a column of the outer row. Here we use that link with the EXISTS operator.
What EXISTS does
EXISTS is a predicate that takes a subquery. It is true if the subquery returns at least one row, and false if it returns none. It does not care what the rows contain, how many there are, or what any column holds.
That makes it a direct translation of the question "does this row have at least one related row?" Does this customer have an order? Does this product appear in any order item? Does this employee manage anyone?
The tables in this chapter are small, so you can follow the results by hand.
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
);
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL
);
INSERT INTO customers VALUES (1, 'Ana'), (2, 'Ben'), (3, 'Chi');
INSERT INTO orders VALUES
(101, 1, '2026-01-10', 50.00),
(102, 1, '2026-02-05', 150.00),
(103, 2, '2026-03-01', 80.00);
INSERT INTO products VALUES (1, 'Laptop'), (2, 'Mouse');
INSERT INTO order_items VALUES
(101, 2, 1),
(102, 1, 1),
(103, 2, 2);Ana has two orders, Ben has one, and Chi has none.
The basic pattern
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
);This returns Ana and Ben. Chi has no matching orders, so the inner query returns nothing for her and EXISTS is false.
The condition o.customer_id = c.customer_id is the correlation. Without it, the inner query would not depend on the outer row at all.
How the engine reasons about it
Think of the query as a loop, even though the optimizer may run it differently:
- Take one row from
customers. - Substitute that row's
customer_idinto the inner query. - Ask whether the inner query returns at least one row.
- Keep the customer if it does.
The diagram shows this for one outer row.
Two properties follow from this model.
- It stops early.
EXISTSonly needs one row. Most databases stop searchingordersfor that customer at the first match, even if the customer has a thousand orders. This is a common reason to prefer it over counting rows. - It is a yes or no answer.
EXISTSnever produces NULL or UNKNOWN. This matters later, when we compare it withINin a following chapter.
Adding conditions to the inner query
The inner query can have any filters you like. Only rows that pass them count as a match.
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.customer_id
AND o.total > 100
);This returns only Ana, because only her order 102 exceeds 100. The correlation says which orders belong to the customer. The extra filter says which of those orders count.
You can also put joins inside the subquery. This finds customers who have ordered a laptop:
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.customer_id = c.customer_id
AND p.name = 'Laptop'
);This returns Ana. The joins are internal to the inner query. They never multiply the rows of the outer query, because the outer query only sees a true or false answer for each customer. This is the main practical advantage over writing the same question as an outer join.
One EXISTS, or two?
Each EXISTS is evaluated separately, so each one may be satisfied by a different inner row. This is easy to get wrong when you need two conditions to hold.
Consider the question "customers with an order in January and an order in February."
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
AND o.order_date >= '2026-01-01' AND o.order_date < '2026-02-01'
)
AND EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
AND o.order_date >= '2026-02-01' AND o.order_date < '2026-03-01'
);This returns Ana. Two separate EXISTS predicates are right here because the two conditions need two different rows.
Now consider the question "customers with an order over 100 placed in March." Those two conditions must hold for the same row, so they belong in one inner query. Two separate EXISTS predicates would be wrong, because one order could satisfy the first and a different order the second.
The rule: if the conditions describe a single related row, use one EXISTS with AND inside. If they describe different related rows, use one EXISTS for each.
Combining EXISTS with other predicates
EXISTS is a normal boolean predicate. You can combine it with AND, OR, and NOT, and mix it with ordinary column conditions.
SELECT c.customer_id, c.name
FROM customers c
WHERE c.name LIKE 'A%'
OR EXISTS (
SELECT 1 FROM orders o
WHERE o.customer_id = c.customer_id
AND o.total >= 80
);This returns Ana, because her name starts with A, and Ben, because his order 103 has a total of 80. Chi matches neither condition.
An OR between an EXISTS and another predicate can be hard for some optimizers to turn into a join. If such a query is slow on a large table, test it with the EXISTS branches separated using UNION, then compare the plans.
Common errors
Forgetting the correlation
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
);This subquery does not mention c. It is not correlated, so it asks whether orders has any rows at all. The answer is the same for every customer. Since orders is not empty, the query returns all three customers, including Chi. If an EXISTS query returns everyone or no one, check the correlation first.
Unqualified column names
SELECT c.customer_id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1 FROM orders o
WHERE customer_id = customer_id
);SQL resolves an unqualified name by looking at the innermost query first. Both customer_id references resolve to orders.customer_id, so the condition compares each order with itself. It is true for every order whose customer_id is not NULL, and the query again returns all customers. Always qualify both sides of a correlation with their aliases, as in o.customer_id = c.customer_id.
Using the wrong key
Correlating on the wrong column can give plausible-looking but wrong results. If you wrote o.order_id = c.customer_id, the query would match order 101 against a customer with id 101, which is nonsense. When a result looks wrong, read the correlation aloud: "an order whose customerid equals this customer's customerid."
Expecting EXISTS to return data
EXISTS answers a yes or no question. It cannot return the matching order's date or total to the outer query. If you need columns from the related rows, use a join. If you need a single summary value, use a correlated scalar subquery, which a later chapter covers.
EXISTS and NULL
A correlation comparison such as o.customer_id = c.customer_id is UNKNOWN when either side is NULL. In a WHERE clause, UNKNOWN does not count as a match. An order with a NULL customer_id therefore never matches any customer, and it does not make EXISTS true for anyone.
The EXISTS predicate itself is always true or false. If the inner query finds no rows because every comparison was UNKNOWN, EXISTS is false, not UNKNOWN. This is why EXISTS behaves predictably when NULLs appear in the data. The same cannot be said for IN and NOT IN, which a later chapter explains.
Checking your understanding by hand
Before running an EXISTS query on real data, work out the result for a few outer rows.
- Pick an outer row, such as Chi.
- Replace the correlated reference with that row's value. For Chi,
o.customer_id = c.customer_idbecomeso.customer_id = 3. - Run the inner query alone and see whether it returns any rows.
You can run step 3 directly:
SELECT 1
FROM orders o
WHERE o.customer_id = 3;This returns no rows, so EXISTS is false for Chi. This technique is a reliable way to debug a correlated query.
Decision notes
- Use
EXISTSwhen the question is "does at least one related row exist," especially when the related table has many rows per outer row. - Use a join when you need columns from the related rows in the result.
- Prefer
EXISTSoverCOUNT(*) > 0. The count has to examine every matching row, whileEXISTScan stop at the first. - Keep the correlation condition and any filters together in the inner
WHERE, and qualify every column with an alias.
Exercise
Using the tables from this chapter, write a query that returns the names of customers who have at least one order containing the product named 'Mouse' with a quantity of 2 or more. Why must the quantity condition and the product condition sit in the same EXISTS rather than in two separate ones?
Show answer
SELECT c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o JOIN orderitems oi ON oi.orderid = o.orderid JOIN products p ON p.productid = oi.productid WHERE o.customerid = c.customer_id AND p.name = 'Mouse' AND oi.quantity >= 2); This returns Ben, whose order 103 has two mice. Both conditions describe the same order item row, so they must be tested together. With two separate EXISTS predicates, a customer could pass by buying a mouse in quantity 1 in one order and some other product in quantity 2 in another order. Each predicate would find a different row, and the combined result would be wrong.
Exercise
A colleague writes WHERE EXISTS (SELECT 1 FROM orders o WHERE customerid = customerid) and finds that every customer is returned, even customers with no orders. Explain why and fix the query.
Show answer
Unqualified column names resolve to the innermost table in scope, so both customerid references mean o.customerid. The condition compares each order's customerid with itself, which is true for any order with a non-NULL customerid. EXISTS is therefore true for every outer row whenever such an order exists. The fix is to qualify both sides: WHERE o.customerid = c.customerid, with the outer table aliased as c.