Subqueries

Basic SQL
≈ 1 min read

A subquery is a SELECT inside another SQL statement

A subquery is a nested SELECT whose result is used by an outer query. The inner query may return one value, several rows, or an entire table-like result — the allowed shape depends on where it is used.

SELECT name
FROM products
WHERE price > (
    SELECT AVG(price)
    FROM products
);

The inner query calculates the average price. The outer query receives that single number and uses it in the price > ... condition.

Understand the inner result first

A useful way to read a subquery is from the inside out. First determine which columns and how many rows the inner SELECT can return, then see how the outer query can use a result of that shape.

A subquery is not always better than a JOIN. The same task can often be expressed in several ways. At this stage, it is more important to choose a form that clearly expresses the query's meaning; optimization and execution plans are covered later.