What is a subquery and where can it be used?
A subquery is a SELECT in parentheses inside another query, and it can go in WHERE, HAVING, SELECT and FROM. A scalar subquery returns one value, a list subquery for IN or ANY one column, EXISTS only whether a row exists, and a subquery in FROM acts as a temporary table. A scalar with several rows raises an error, with zero rows it gives NULL.
SQL · Subqueries, CTE, sets
A "greater than average" threshold was typed into the query as a number. The data changed and the report lied. How to avoid the number?
In a query that finds large transactions someone typed the threshold 188.33: they once counted the average by hand. The test was green until a test row was added. Now the average is different and the threshold stayed the same. A subquery cures this class of bug: the query itself computes the threshold at run time. This lesson covers where a subquery can go, how its kinds differ and where it breaks.
How it works and why. A subquery is a SELECT in parentheses inside another query. The database runs it as part of the outer one, so its result is always fresh. The kind of subquery decides what shape it must return, and that is where almost all mistakes come from. The data used below (table transactions):
| id | account_id | amount | status |
|---|---|---|---|
| 1 | 10 | 100 | completed |
| 2 | 10 | 300 | completed |
| 3 | 11 | 50 | failed |
| 4 | 12 | 200 | completed |
| 5 | 12 | 400 | completed |
| 6 | 13 | 80 | completed |
Where a subquery can go
A scalar subquery returns one row with one column and stands where a value is expected: in a comparison or in SELECT. With zero rows it yields NULL, and a comparison with it selects nothing. With more than one row the database raises an error. A list subquery (IN, ANY) returns one column and any number of rows. EXISTS only checks whether at least one row exists, the columns do not matter. A subquery in FROM works as a temporary table, so WHERE or JOIN can be applied to it. MySQL and PostgreSQL before version 16 require an alias for it, so people always write one. A correlated subquery refers to columns of the outer query, so logically it runs once per outer row.
Example: from a hard-coded number to a subquery. The starting query:
-- the threshold is typed in as a number, counted by hand once
SELECT id, amount
FROM transactions
WHERE amount > 188.33;
The average of six amounts is 1130 / 6 ≈ 188.33, and the query returns transactions 2, 4, 5 (amounts 300, 200, 400). Add a seventh row with 20, the average drops, and the query still cuts by the old threshold. The correct form:
-- the query computes the threshold itself: ids 2, 4, 5
SELECT id, amount
FROM transactions
WHERE amount > (SELECT AVG(amount) FROM transactions);
A correlated subquery is useful for "the largest within a group":
-- correlated: the largest transaction of each account
-- result: ids 2, 3, 5, 6
SELECT t.id, t.account_id, t.amount
FROM transactions t
WHERE t.amount = (SELECT MAX(t2.amount)
FROM transactions t2
WHERE t2.account_id = t.account_id);
If an account has two transactions with the same maximum amount, both come back. The typical case for a subquery in FROM: aggregate first, then filter on the aggregate:
-- a subquery in FROM: the per-account total first, then the filter
SELECT s.account_id, s.total
FROM (
SELECT account_id, SUM(amount) AS total
FROM transactions
WHERE status = 'completed'
GROUP BY account_id
) AS s
WHERE s.total > 250;
-- accounts 10 (400) and 12 (600); 13 has only 80
If a scalar subquery returns several rows, the database stops the query with an error:
SELECT id FROM transactions
WHERE amount = (SELECT amount FROM transactions WHERE status = 'completed');
-- ERROR: more than one row returned by a subquery used as an expression
The same threshold written two ways
WHERE amount > 188.33
The number goes stale as soon as the data changes. The test passes while old and new values happen to match.
WHERE amount > (SELECT AVG…)
The threshold is computed at run time and always matches the data in the table.
Limits and alternatives. The PostgreSQL planner often runs a correlated scalar subquery with an aggregate once per outer row (the plan shows SubPlan), so on large tables it can be slow. Then it is replaced with a JOIN to a grouped table or with a window function. IN and EXISTS are usually turned into a join (a semi-join) by the planner. Deep nesting reads badly, and CTEs exist for that. Decide by EXPLAIN, not by a guess.
Typical mistakes.
- A scalar subquery that returns several rows: the error
more than one row returned by a subquery used as an expression. Add an aggregate,LIMIT 1withORDER BY, or switch=toIN. - A scalar subquery with no rows yields NULL, and the condition selects nothing with no message.
- A subquery in
FROMwithout an alias: an error in MySQL and in PostgreSQL before 16. - A correlated subquery without table aliases: the inner
account_idis compared with itself and the condition is always true. - A typed-in number instead of a subquery: the test depends on the state of the data.
Check yourself
The query SELECT id FROM transactions WHERE amount = (SELECT amount FROM transactions WHERE status = 'completed') fails. Why, if the sample table has five completed transactions?
Answer
A scalar subquery must return at most one row, and here it returns five. The database answers with a more-than-one-row error. The fix depends on the intent: IN for any match, MAX or AVG for a single value.
How does a subquery in FROM differ from a subquery in WHERE in the shape of its result?
Answer
In FROM a subquery returns a table with any number of columns and rows, and it needs an alias. In WHERE it must return a value (scalar), a one-column list (IN) or only the fact that a row exists (EXISTS).