QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Subqueries, CTEs, set operations

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):

idaccount_idamountstatus
110100completed
210300completed
31150failed
412200completed
512400completed
61380completed

Where a subquery can go

WHERE amount > (…)scalar: 1 row, 1 columnWHERE id IN (…)list: 1 column, any number of rowsWHERE EXISTS (…)only "is there at least one row?"FROM (…) AS xa table: anything, but with an alias
Figure 1. The place of a subquery decides which shape of result it must return.

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

Wrong

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.

Right

WHERE amount > (SELECT AVG…)

The threshold is computed at run time and always matches the data in the table.

Figure 2. A computed value beats a typed-in one.

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 1 with ORDER BY, or switch = to IN.
  • A scalar subquery with no rows yields NULL, and the condition selects nothing with no message.
  • A subquery in FROM without an alias: an error in MySQL and in PostgreSQL before 16.
  • A correlated subquery without table aliases: the inner account_id is 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).

In an interview. Junior: A subquery is a query in parentheses inside another one. It can return one value for a comparison, a list for IN or a table in FROM. For example, I find transactions above the average with a scalar subquery instead of typing a number. Middle/Senior: I talk about the shape of the result: a scalar must return at most one row or it is an error, and zero rows gives NULL and a silently empty result. A correlated subquery logically runs per row, so on large tables I read EXPLAIN and, if needed, rewrite it as a JOIN with grouping or a window function. I split complex queries into CTEs.

More articles in this chapter