Concept · Advanced SQL

Subquery

A subquery is a SELECT query written in parentheses inside another query. Its result can be a single value, a list or an intermediate table, and it can be used in WHERE, FROM or SELECT.

Subquery example

We want the customers who have at least one order whose total is above the average of all orders:

SQL
SELECT name
FROM customers
WHERE id IN (
  SELECT customer_id
  FROM orders
  WHERE total > (
    SELECT AVG(total)
    FROM orders
  )
)
ORDER BY name;

The innermost subquery calculates an average of roughly 218.44. The next one finds the ids of customers with orders above that figure. The outer query turns those ids into names.

What changes from case to case

Three common forms

  • Scalar: returns a single value and can be used in a comparison.
  • With IN or EXISTS: decides whether a row meets a related condition.
  • In FROM: acts as a temporary table and needs an alias on many engines.
Structure example
SELECT columns
FROM table_name
WHERE value > (
  SELECT AVG(value)
  FROM table_name
);

Correlated subquery

A correlated subquery uses values from the row the outer query is evaluating. It can express very clear rules with EXISTS, but conceptually it is evaluated for each outer row. The optimiser may rewrite it, so do not guess its cost without looking at the plan.

Common mix-ups with subqueries

Using a scalar subquery that can return several rows

A comparison such as price = (SELECT price FROM products) says the inner query must supply a single value. PostgreSQL raises an error if it gets several rows; SQLite takes the first and discards the rest. Relying on either accident makes the intent fragile.

Alternatives depending on the question
-- One calculated value
WHERE price > (SELECT AVG(price) FROM products)

-- Membership in a list
WHERE category_id IN (SELECT id FROM categories)

-- Existence of a related row
WHERE EXISTS (
  SELECT 1
  FROM orders AS p
  WHERE p.customer_id = customers.id
)

Usa LIMIT 1 only when you really want one particular row, and pair it with an ORDER BY that says which one.

A scalar subquery must return a single row and a single column

A subquery is a query inside another query. When it is used as a value, for example on the right of a comparison, it must return one row and one column. If it returns several rows, most engines raise an error; others silently pick a value, so check the number of rows before you rely on it.

An uncorrelated subquery is calculated independently of the outer query, like the overall average in the example. A correlated one uses columns from the outer row and is conceptually evaluated for each row, which can cost more. To test for existence, EXISTS usually states the intent better than counting rows.

Check the result with a small table: work out by hand the value the subquery should return and see which rows exceed it. Check for nulls: a comparison with a missing value is not true, so that row does not get through the filter. If the logic gets complicated, a named CTE may be easier to read.

Self-contained case to check in SQLite

We look for orders whose total is above the average of all orders.

Data and query · SQLite
WITH orders(id, total) AS (
  VALUES (1, 30), (2, 50), (3, 90)
)
SELECT id, total
FROM orders
WHERE total > (SELECT AVG(total) FROM orders)
ORDER BY id;
Verified result of the self-contained case
idtotal
390

The average is about 56.67; only the order of 90 is above it. The subquery returns a single row with a single column.

Check your interpretation: Which orders would be above the average if we added one of 200?

Show answer

Only the one for 200. The average would become 92.5 (370 / 4) and the order for 90 would fall below it.

Technical questions: PostgreSQL: subquery expressions (opens in a new tab).