Subqueries
Overview
Because every query returns a table, the result of one query can be used inside another. A query inside a query is called a subquery (or inner query). Subqueries let you answer questions in steps — first find the average price, then find the products above it — without running two queries by hand.
Scalar subqueries: a single value
Which products cost more than average? You could find the average first:
SELECT avg(price) FROM products; avg
---------------------
26.3250000000000000
(1 row)…and then type WHERE price > 26.325 into a second query. But the number would go stale as soon as a price changed. Instead, put the first query inside the second, in brackets:
SELECT name, price
FROM products
WHERE price > (SELECT avg(price) FROM products)
ORDER BY price DESC; name | price
-----------------+-------
Burr Grinder | 89.00
Electric Kettle | 59.90
Glass Teapot | 32.00
(3 rows)The inner query runs (conceptually) first, produces one number, and the outer query uses it like a constant. A subquery that returns exactly one row and one column is called a scalar subquery, and it can go anywhere a single value can — in WHERE, in the select list, even in a calculation:
SELECT name, price,
round(price - (SELECT avg(price) FROM products), 2) AS vs_average,
round(100.0 * price / (SELECT max(price) FROM products)) AS pct_of_dearest
FROM products
WHERE category_id = 2
ORDER BY price DESC; name | price | vs_average | pct_of_dearest
------------------------+-------+------------+----------------
Darjeeling First Flush | 18.00 | -8.33 | 20
Jasmine Green | 12.75 | -13.58 | 14
Assam Breakfast | 9.50 | -16.83 | 11
Chamomile Calm | 8.00 | -18.33 | 9
(4 rows)If a “scalar” subquery returns more than one row, PostgreSQL stops with an error; if it returns no rows, the value is NULL:
SELECT name FROM products
WHERE category_id = (SELECT id FROM categories WHERE name LIKE '%e%');ERROR: more than one row returned by a subquery used as an expressionAll four category names contain an “e”, so the subquery returned four rows where one was required.
List subqueries: IN
A subquery that returns one column of many rows can be used with IN. Customers who have a pending order:
SELECT first_name, city
FROM customers
WHERE id IN (SELECT customer_id
FROM orders
WHERE status = 'pending')
ORDER BY first_name; first_name | city
------------+-------
Asha | Pune
Dee | Lagos
(2 rows)Read it inside out: the inner query lists the customer ids with pending orders (1 and 4); the outer query keeps customers whose id is in that list. Unlike a join, IN never duplicates rows — a customer with three pending orders would still appear once.
NOT IN finds the opposite — products that appear in no order:
SELECT name
FROM products
WHERE id NOT IN (SELECT product_id FROM order_items); name
--------------
Glass Teapot
(1 row)That works here, but NOT IN has a nasty trap when the subquery can return NULL. The next lesson explains it and shows the safer NOT EXISTS.
ANY and ALL
IN is shorthand for = ANY. The general forms compare a value with every row of a one-column subquery:
x > ANY (subquery)— greater than at least one of them;x > ALL (subquery)— greater than every one of them.
Products more expensive than every tea:
SELECT name, price
FROM products
WHERE price > ALL (SELECT price FROM products WHERE category_id = 2)
ORDER BY price; name | price
-------------------+-------
Pour-Over Dripper | 24.00
Gift Card | 25.00
Glass Teapot | 32.00
Electric Kettle | 59.90
Burr Grinder | 89.00
(5 rows)That’s the same as price > (SELECT max(price) …), and the max version is usually clearer. ANY and ALL come into their own with operators that have no simple aggregate equivalent.
Derived tables: subqueries in FROM
A subquery can also produce a whole table that the outer query reads from. This is called a derived table, and it must have an alias. It’s the natural way to aggregate in two steps — for example, the average order value, where each order’s value must first be added up from its items:
SELECT count(*) AS orders,
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 t; orders | avg_order_value | biggest_order
--------+-----------------+---------------
24 | 50.58 | 113.00
(1 row)You can’t write avg(sum(...)) directly — aggregates can’t be nested — so the inner query produces one row per order and the outer query aggregates those rows. You saw the same technique in the previous lesson, joining a pre-aggregated subquery to avoid fan-out.
Derived tables can be joined like any table. Each customer’s biggest order:
SELECT c.first_name, max(t.order_total) AS biggest_order
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
JOIN (SELECT order_id, sum(quantity * unit_price) AS order_total
FROM order_items
GROUP BY order_id) AS t ON t.order_id = o.id
GROUP BY c.id, c.first_name
ORDER BY biggest_order DESC
LIMIT 3; first_name | biggest_order
------------+---------------
Ben | 113.00
Hugo | 89.00
Elena | 77.50
(3 rows)Subqueries in the select list
A scalar subquery in SELECT adds a value to each row. Each category with its number of products and its cheapest price:
SELECT c.name,
(SELECT count(*) FROM products AS p WHERE p.category_id = c.id) AS products,
(SELECT min(price) FROM products AS p WHERE p.category_id = c.id) AS cheapest
FROM categories AS c
ORDER BY c.name; name | products | cheapest
-------------+----------+----------
Accessories | 0 |
Coffee | 3 | 11.25
Equipment | 4 | 24.00
Tea | 4 | 8.00
(4 rows)Notice that these subqueries refer to c.id from the outer query — they’re re-evaluated for each category. That makes them correlated subqueries, the subject of the next lesson. Here the same result could come from a LEFT JOIN with GROUP BY; which one you write is a matter of clarity.
Subquery or join?
Many questions can be written either way. Customers with a pending order, as a join:
SELECT DISTINCT c.first_name, c.city
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
WHERE o.status = 'pending'
ORDER BY c.first_name; first_name | city
------------+-------
Asha | Pune
Dee | Lagos
(2 rows)Same result as the IN version, but it needs DISTINCT to undo the duplicates the join could create. Some guidelines:
- Need columns from both tables in the result? Use a join.
- Only filtering by another table (“customers who have…”)?
INorEXISTSoften reads more naturally and can’t duplicate rows. - Aggregating in two steps? Use a derived table — or a CTE, which you’ll meet at the end of this chapter and which makes multi-step queries much easier to read.
PostgreSQL’s planner often turns subqueries into joins internally, so performance is usually similar; write for clarity first.
Tip: when building a query with a subquery, run the inner query on its own first and check its output. If the inner part is right, the outer part is usually easy.
Above average, and waiting
Two questions, one subquery each. First: which products cost more than the average product price? Return name and price, most expensive first, using a scalar subquery in WHERE (you should get three products). Second: which customers currently have a pending order? Return their first_name and email, sorted by first name, using IN with a subquery on orders — no join.
-- 1. Products above the average price
SELECT name, price
FROM products
WHERE price > ___
ORDER BY price DESC;
-- 2. Customers with a pending order-- 1. Products above the average price
SELECT name, price
FROM products
WHERE price > (SELECT avg(price) FROM products)
ORDER BY price DESC;
-- 2. Customers with a pending order
SELECT first_name, email
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE status = 'pending')
ORDER BY first_name;Summary
- A subquery is a complete SELECT inside brackets, used inside another query.
- A scalar subquery returns one row and one column and can be used anywhere a single value can.
- A subquery returning one column can feed IN, or ANY / ALL comparisons.
- A subquery in FROM acts as a temporary table (a derived table) and must be given an alias.
- Many subqueries can be rewritten as joins; choose whichever expresses the question more clearly.