SQL Subqueries
A subquery is a query inside another query, wrapped in parentheses. Use it when one answer depends on another, like “drinks that cost more than the average”.
Updated December 1, 2026
Syntax
SELECT columns
FROM table_name
WHERE column > (SELECT AGGREGATE(column) FROM table_name);
Compare to a single value
The inner query returns one number, the average price. The outer query uses it like a constant.
SELECT name, price
FROM drinks
WHERE price > (SELECT AVG(price) FROM drinks)
ORDER BY price DESC;
| name | price |
|---|---|
| Matcha Latte | 5.25 |
| Mocha | 5 |
| Cold Brew | 4.75 |
| Chai Latte | 4.75 |
| Latte | 4.5 |
| Cappuccino | 4.25 |
Filter with a list
With IN, the subquery can return many values: departments that have someone earning over $150,000.
SELECT name
FROM departments
WHERE id IN (SELECT department_id FROM employees WHERE salary > 150000);
| name |
|---|
| Engineering |
| Sales |
Query a subquery’s result
A subquery in FROM acts like a temporary table. Here we total each order, then average those totals.
SELECT COUNT(*) AS orders, ROUND(AVG(total), 2) AS avg_order_value
FROM (
SELECT i.order_id, SUM(i.quantity * p.price) AS total
FROM order_items AS i
JOIN products AS p ON p.id = i.product_id
GROUP BY i.order_id
) AS order_totals;
| orders | avg_order_value |
|---|---|
| 10 | 115.25 |
Common mistakes
- Using
=with a subquery that returns several rows. UseIN, or make sure it returns one value. - Forgetting the alias for a subquery in
FROM; most databases require one. - Nesting subqueries several levels deep. A CTE is far easier to read.
Practice Subqueries interactively
Write real queries in your browser and get instant feedback in the lesson “Subqueries in WHERE” (Unit 6). New learners can start free from the first lesson.
Frequently asked questions
Subquery or JOIN: which is better?
Use whichever reads more clearly. Databases often run them the same way. JOINs are better when you need columns from both tables.
What is a correlated subquery?
One that refers to the outer query’s row, so it runs once per row. It’s powerful but can be slow; window functions often do the same job faster.