A query inside a query
Sometimes the number you want to compare against isn't known yet. "Which products cost more than average?" needs the average first. A subquery works it out inside the main query:
SELECT name, list_price
FROM products
WHERE list_price > (SELECT AVG(list_price) FROM products)The part in brackets runs first and gives one number. The outer query then uses it like any other value. A subquery that returns exactly one value is called a scalar subquery, and you can use it anywhere a single number would go.
Subqueries also work with IN, when the inner query returns a list:
SELECT name
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE order_date >= '2026-10-01')That's every customer who has ordered since 1 October 2026. Each customer appears once, however
many orders they placed, because the outer query reads customers, not orders.