PostgreSQL Subqueries
A subquery is a SELECT inside another statement, written in parentheses. You have already met a few (IN (SELECT …), EXISTS (…)). This lesson collects the different places a subquery can go and what each one must return.
| Where | Must return | Example |
|---|---|---|
| In an expression (scalar subquery) | one row, one column | price > (SELECT avg(price) FROM books) |
With IN, ANY, ALL |
one column, any number of rows | id IN (SELECT book_id FROM order_items) |
With EXISTS |
anything | EXISTS (SELECT 1 FROM …) |
In FROM (derived table) |
any table, needs an alias | FROM (SELECT …) AS t |
Scalar subqueries
A scalar subquery produces a single value that can be used like a constant. Books priced above the average:
SELECT title, price
FROM books
WHERE price > (SELECT avg(price) FROM books)
ORDER BY price DESC; title | price
---------------------------+-------
Postgres in Practice | 44.00
Rust for Curious Minds | 42.50
Learning SQL the Calm Way | 39.90
Algorithms on a Napkin | 35.00
Empires of Sand | 27.00
The Age of Canals | 24.95
Clockwork Garden | 21.00
(7 rows)
Scalar subqueries also work in the select list. Here each row shows how far a book's price is from the average:
SELECT title, price,
round(price - (SELECT avg(price) FROM books), 2) AS diff_from_avg
FROM books
WHERE category_id = 5; title | price | diff_from_avg
------------------------+-------+---------------
Empires of Sand | 27.00 | 6.11
The Age of Canals | 24.95 | 4.06
A Short History of Tea | 19.50 | -1.39
(3 rows)
If a scalar subquery returns more than one row, the statement fails:
SELECT title FROM books WHERE author_id = (SELECT id FROM authors WHERE country = 'UK' OR country = 'Japan');ERROR: more than one row returned by a subquery used as an expression
Correlated subqueries
A correlated subquery refers to a column of the outer query, so it is evaluated once per outer row. The most expensive book within each category:
SELECT b.title, b.category_id, b.price
FROM books b
WHERE b.price = (SELECT max(b2.price) FROM books b2 WHERE b2.category_id = b.category_id)
ORDER BY b.category_id; title | category_id | price
----------------------+-------------+-------
Winter in Sofia | 1 | 17.80
Clockwork Garden | 2 | 21.00
The Quiet Witness | 3 | 13.49
Postgres in Practice | 4 | 44.00
Empires of Sand | 5 | 27.00
Ten Tiny Dragons | 6 | 8.99
(6 rows)
And the number of orders per customer, computed in the select list:
SELECT c.first_name,
(SELECT count(*) FROM orders o WHERE o.customer_id = c.id) AS orders,
(SELECT max(order_date) FROM orders o WHERE o.customer_id = c.id) AS last_order
FROM customers c
WHERE c.id <= 5
ORDER BY c.id; first_name | orders | last_order
------------+--------+------------
Anna | 3 | 2024-07-09
Ben | 3 | 2024-11-11
Chloé | 1 | 2024-02-14
David | 2 | 2024-09-14
Emma | 2 | 2024-10-05
(5 rows)
Subqueries in FROM
A subquery in FROM acts as a temporary table. It is useful for aggregating in two steps, for example "the average order value", which first needs the total of each order:
SELECT round(avg(order_total), 2) AS avg_order_value,
max(order_total) AS biggest_order
FROM (
SELECT order_id, sum(quantity * unit_price) AS order_total
FROM order_items
GROUP BY order_id
) AS totals; avg_order_value | biggest_order
-----------------+---------------
43.95 | 117.40
(1 row)
LATERAL: a subquery per row
A normal subquery in FROM can't see other tables of the same FROM. With LATERAL it can, and it runs once for each row on its left. It is the cleanest way to get "the top N per group":
SELECT c.name AS category, top.title, top.price
FROM categories c
CROSS JOIN LATERAL (
SELECT b.title, b.price
FROM books b
WHERE b.category_id = c.id
ORDER BY b.price DESC
LIMIT 2
) AS top
WHERE c.id <= 3
ORDER BY c.id, top.price DESC; category | title | price
-----------------+--------------------+-------
Fiction | Winter in Sofia | 17.80
Fiction | Paper Lanterns | 15.20
Science Fiction | Clockwork Garden | 21.00
Science Fiction | Signal from Kepler | 18.00
Mystery | The Quiet Witness | 13.49
Mystery | The Map Thief | 12.99
(6 rows)
Subqueries in data changes
Subqueries work in INSERT, UPDATE and DELETE too. Give a 20 % discount on books that have never been sold:
UPDATE books
SET price = round(price * 0.8, 2)
WHERE id NOT IN (SELECT book_id FROM order_items)
RETURNING title, price; title | price
-------------------+-------
Harbor Lights | 10.00
The Age of Canals | 19.96
Winter in Sofia | 14.24
(3 rows)
UPDATE 3
Tip: Long queries with several nested subqueries get hard to read. The next lesson, CTEs, shows how to name each step with
WITHinstead.
Test yourself
What must a scalar subquery return?
- Any number of rows
- At most one row with one column
- Exactly two columns
- A table alias
What makes a subquery 'correlated'?
- It uses JOIN
- It refers to a column of the outer query
- It returns many rows
- It is in the FROM clause
Which keyword lets a subquery in FROM refer to tables listed before it?
- CORRELATED
- LATERAL
- WITH
- USING