← SQL and databases

Subqueries that return one value

Use the answer of one query inside another.

Start this lesson

A subquery is a query inside parentheses inside another query. If it returns a single value, you can use it anywhere you would write a number. "Books longer than average" needs the average first: WHERE pages > (SELECT AVG(pages) FROM books). The inner query runs, gives one number, and the outer query uses it.

SELECT name, price FROM products
WHERE price = (SELECT MAX(price) FROM products);

The inner query finds the highest price (60). The outer one shows the product with that price, so you see its name too.

You cannot write WHERE pages > AVG(pages), because aggregates are not allowed in WHERE. The subquery is the way around that.