SQL subqueries
A subquery is a query inside another query. It can return one value for a comparison, a list for IN, or a whole table to select from. For longer logic, a CTE (WITH) does the same and reads more easily.
One value: compare with an average
Orders above the average order:
SELECT * FROM ordersWHERE amount > (SELECT AVG(amount) FROM orders);
A list: IN or EXISTS
Customers who ordered in 2026:
SELECT name FROM customers cWHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id AND o.order_date >= '2026-01-01');
This is a correlated subquery: it runs per customer and refers to c.id from the outer query.
A table: subquery in FROM
Average revenue per customer, in two steps:
SELECT AVG(total) FROM ( SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id) t;
The same with a CTE
WITH totals AS ( SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id)SELECT AVG(total) FROM totals;
Common mistake
A subquery used with = must return exactly one row. If it can return more, use IN, or you get an error (or, in SQLite, a silently wrong result based on the first row).
Practise subqueries
Updated November 2026.