EXISTS and correlated subqueries
Overview
The subqueries in the previous lesson were independent: you could run the inner query on its own. A correlated subquery is different — it refers to the row the outer query is currently looking at, so it’s re-evaluated for each one. That lets you ask per-row questions: is this product priced above the average for its category? Does this customer have any orders? Paired with EXISTS, correlated subqueries are the cleanest way to test whether related rows exist.
A subquery that depends on the outer row
Which products cost more than the average price in their own category?
SELECT p.name, p.category_id, p.price
FROM products AS p
WHERE p.price > (SELECT avg(p2.price)
FROM products AS p2
WHERE p2.category_id = p.category_id)
ORDER BY p.category_id, p.price DESC; name | category_id | price
------------------------+-------------+-------
Ethiopian Yirgacheffe | 1 | 14.50
Darjeeling First Flush | 2 | 18.00
Jasmine Green | 2 | 12.75
Burr Grinder | 3 | 89.00
Electric Kettle | 3 | 59.90
(5 rows)The inner query mentions p.category_id — a column of the outer query’s current row. For the Ethiopian Yirgacheffe it computes the coffee average; for the Darjeeling, the tea average; and so on. Two aliases of the same table (p and p2) keep the two levels apart, just as in a self-join.
The gift card is absent: its category is NULL, p2.category_id = NULL matches nothing, and comparing with a NULL average isn’t true.
Another classic: each customer’s most recent order.
SELECT o.customer_id, o.id, o.ordered_at::date AS day, o.status
FROM orders AS o
WHERE o.ordered_at = (SELECT max(o2.ordered_at)
FROM orders AS o2
WHERE o2.customer_id = o.customer_id)
ORDER BY o.customer_id; customer_id | id | day | status
-------------+----+------------+-----------
1 | 23 | 2026-11-20 | pending
2 | 21 | 2026-10-27 | paid
3 | 19 | 2026-09-19 | delivered
4 | 24 | 2026-11-29 | pending
5 | 16 | 2026-07-08 | delivered
6 | 22 | 2026-11-08 | paid
7 | 18 | 2026-09-01 | shipped
8 | 20 | 2026-10-03 | shipped
(8 rows)You’ll see a more flexible way to do “the latest row per group” with window functions in the next chapter.
EXISTS: is there at least one?
EXISTS (subquery) is true if the subquery returns any rows at all, and false if it returns none. It doesn’t care what the rows contain, so by convention the subquery selects a constant: SELECT 1.
Customers who have at least one delivered order:
SELECT c.first_name, c.country
FROM customers AS c
WHERE EXISTS (SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
AND o.status = 'delivered')
ORDER BY c.first_name; first_name | country
------------+-----------
Asha | India
Ben | UK
Chen | Singapore
Dee | Nigeria
Elena | Spain
Farhan | India
Grace | USA
Hugo | France
(8 rows)EXISTS can stop searching as soon as it finds one matching row, and — like IN — it never duplicates outer rows, however many matches there are.
NOT EXISTS: finding what’s missing
NOT EXISTS is true when there are no related rows. It’s the clearest way to write “customers who never…”, “products that were never…”:
SELECT c.first_name
FROM customers AS c
WHERE NOT EXISTS (SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id)
ORDER BY c.first_name; first_name
------------
Isha
Jack
(2 rows)That’s the same answer as the LEFT JOIN … IS NULL anti-join in Outer joins. Both are fine; many people find NOT EXISTS reads closer to the question, and PostgreSQL executes both the same way.
The NOT IN trap
Why not just use NOT IN? Because of NULL. Which categories have no products?
SELECT name
FROM categories
WHERE id NOT IN (SELECT category_id FROM products); name
------
(0 rows)No rows — yet Accessories clearly has no products. The cause is the gift card’s NULL category_id. NOT IN (1, 2, 3, NULL) means “not 1 and not 2 and not 3 and not NULL”, and “4 is not NULL” — written 4 <> NULL — is unknown, never true. One NULL anywhere in the list makes NOT IN return nothing at all, silently.
NOT EXISTS doesn’t have this problem, because it only asks whether matching rows exist:
SELECT cat.name
FROM categories AS cat
WHERE NOT EXISTS (SELECT 1
FROM products AS p
WHERE p.category_id = cat.id); name
-------------
Accessories
(1 row)Rule: use
NOT EXISTSinstead ofNOT IN (subquery). If you must useNOT IN, addWHERE column IS NOT NULLinside the subquery. (INandEXISTS, the positive forms, are both safe.)
Correlated subqueries in SELECT
A correlated scalar subquery in the select list adds a per-row calculation. Each customer with their order count and the date of their last order:
SELECT c.first_name,
(SELECT count(*) FROM orders AS o WHERE o.customer_id = c.id) AS orders,
(SELECT max(o.ordered_at)::date FROM orders AS o WHERE o.customer_id = c.id) AS last_order
FROM customers AS c
ORDER BY orders DESC, c.first_name; first_name | orders | last_order
------------+--------+------------
Asha | 5 | 2026-11-20
Ben | 4 | 2026-10-27
Chen | 3 | 2026-09-19
Dee | 3 | 2026-11-29
Farhan | 3 | 2026-11-08
Elena | 2 | 2026-07-08
Grace | 2 | 2026-09-01
Hugo | 2 | 2026-10-03
Isha | 0 |
Jack | 0 |
(10 rows)Customers without orders get 0 and NULL — no outer join needed. This style is very readable for one or two extra values. For many, a join with GROUP BY is usually more efficient, because each subquery runs separately.
LATERAL: a correlated subquery that returns rows
A scalar subquery can only return one value. What if you want each customer’s two most recent orders, with several columns? A LATERAL subquery in FROM can refer to earlier tables in the same FROM — it’s a correlated subquery that returns a whole table for each outer row:
SELECT c.first_name, recent.id AS order_id, recent.day, recent.status
FROM customers AS c
CROSS JOIN LATERAL (
SELECT o.id, o.ordered_at::date AS day, o.status
FROM orders AS o
WHERE o.customer_id = c.id
ORDER BY o.ordered_at DESC
LIMIT 2
) AS recent
WHERE c.country IN ('India', 'UK')
ORDER BY c.first_name, recent.day DESC; first_name | order_id | day | status
------------+----------+------------+-----------
Asha | 23 | 2026-11-20 | pending
Asha | 17 | 2026-08-12 | delivered
Ben | 21 | 2026-10-27 | paid
Ben | 14 | 2026-06-07 | delivered
Farhan | 22 | 2026-11-08 | paid
Farhan | 15 | 2026-06-25 | cancelled
(6 rows)For each customer, the lateral subquery picks their two latest orders. CROSS JOIN LATERAL drops customers for whom it returns nothing (Isha); LEFT JOIN LATERAL (…) AS recent ON true would keep them. “Top N per group” is the classic job for LATERAL.
How fast are correlated subqueries?
“Evaluated once per row” sounds slow, and on big tables a naive correlated subquery can be. But PostgreSQL’s planner rewrites most EXISTS, NOT EXISTS and IN subqueries into joins (semi-joins and anti-joins), so they’re typically as fast as the equivalent join. Correlated scalar subqueries in SELECT really do run per row, and benefit greatly from an index on the column they look up — here, orders.customer_id. You’ll learn to check with EXPLAIN in chapter 10.
Other databases:
EXISTSand correlated subqueries are universal.LATERALis supported by PostgreSQL, MySQL 8 and Oracle; SQL Server spells itCROSS APPLY/OUTER APPLY.
Who hasn't ordered, and what's expensive?
First, list the first_name and signup_date of customers who have never placed an order, using NOT EXISTS with a correlated subquery on orders (sorted by first name — you should get Isha and Jack). Second, list the name of every category that has at least one product costing more than 50, using EXISTS.
-- 1. Customers with no orders
SELECT c.first_name, c.signup_date
FROM customers AS c
WHERE NOT EXISTS (
-- an order belonging to this customer
)
ORDER BY c.first_name;
-- 2. Categories with a product over 50-- 1. Customers with no orders
SELECT c.first_name, c.signup_date
FROM customers AS c
WHERE NOT EXISTS (
SELECT 1 FROM orders AS o WHERE o.customer_id = c.id
)
ORDER BY c.first_name;
-- 2. Categories with a product over 50
SELECT cat.name
FROM categories AS cat
WHERE EXISTS (
SELECT 1 FROM products AS p
WHERE p.category_id = cat.id AND p.price > 50
);Summary
- A correlated subquery refers to a column of the outer query, so it is evaluated once for each outer row.
- EXISTS (subquery) is true if the subquery returns at least one row; what it selects doesn't matter, so SELECT 1 is the convention.
- NOT EXISTS is the safe way to find rows with no match — NOT IN returns no rows at all if the subquery produces a NULL.
- Correlated subqueries answer per-row questions such as 'above the average for its category' or 'the latest order for this customer'.
- A LATERAL join is a correlated subquery in FROM that can return several columns and rows per outer row, such as each customer's two latest orders.