Sub topic 7
EXISTS and NOT EXISTS: Testing for Related Rows
Assume you know basic SELECT, WHERE, joins, aggregate functions, GROUP BY, NULL, and three-valued logic. This chapter focuses on checking whether related rows exist, rather than returning values from those rows.
What EXISTS Does
EXISTS is a condition that tests whether a subquery returns at least one row. It returns true when a matching row exists and false when no matching row exists.
The selected value inside the subquery does not matter. For that reason, SELECT 1 clearly communicates the intent:
SELECT c.name
FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
);The outer query examines each customer. For that customer, the subquery searches for an order with the same customer_id. Customers with at least one matching order are returned.
The database can stop searching after it finds the first matching order. This makes EXISTS a natural choice when you need to test presence, not count or display related rows.
Correlation With the Outer Query
The condition o.customer_id = c.id connects the inner query to the current row of the outer query. This is a correlated subquery. Conceptually, the database evaluates it like this:
The optimizer may execute the query using a different internal strategy. The row-by-row description is a useful working model, but it is not a promise about the physical execution plan.
NOT EXISTS for Missing Relationships
NOT EXISTS reverses the test. It returns true when the subquery returns no rows.
This query finds customers who have never placed an order:
SELECT c.id, c.name
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
);NOT EXISTS is often clearer than creating a LEFT JOIN and checking for a null value. It states the question directly: “Is there no related row?”
You can also combine several existence tests:
SELECT c.name
FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
AND o.total > 100
)
AND NOT EXISTS (
SELECT 1
FROM support_tickets AS t
WHERE t.customer_id = c.id
AND t.status = 'open'
);This returns customers who have placed an order over 100 but have no open support ticket.
EXISTS Compared With IN
IN compares a value with values returned by a subquery:
SELECT c.name
FROM customers AS c
WHERE c.id IN (
SELECT o.customer_id
FROM orders AS o
WHERE o.total > 100
);EXISTS checks for a related row:
SELECT c.name
FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
AND o.total > 100
);These queries often produce the same result. EXISTS is usually the better expression when the relationship is the main idea. It also avoids the NOT IN and NULL problem: a null value in orders.customer_id does not make NOT EXISTS unknown.
Practical Rules
- Use
EXISTSwhen at least one related row is enough. - Use
NOT EXISTSto find rows with no related match. - Correlate the subquery with the outer row using a clear key relationship.
- Use
SELECT 1because the selected value is irrelevant. - Use
COUNT(*)instead when you need the number of related rows. - Check a query plan when a correlated query runs slowly on large tables.
Exercise
Write a query that returns every department that has at least one employee earning more than 100000.
Show answer
SELECT d.name FROM departments AS d WHERE EXISTS ( SELECT 1 FROM employees AS e WHERE e.department_id = d.id AND e.salary > 100000 );