Subqueries
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.
Check yourself
Exercise review
The mentor knows the solution and will help you reach it independently
Sign in to use the Mentor
The Mentor uses the current exercise and your conversation history.
Sign in
Review the key nuances and the answer after making your own attempt.
Sign in to view the solution
The solution and explanation are available after signing in.
Sign in