SQL subqueries: a query inside a query
Put a whole query in brackets where a value or a list would go. The inner one runs first.
SQL skills · Subqueries and CTEs
What you will learn
Subqueries let you use a number you do not know yet, such as the average, without typing it.
With IN, a subquery can also give a list from another table.
The basics
A subquery is a query in brackets inside another query. The inner one runs first.
SELECT customer, amount
FROM invoices
WHERE amount > (SELECT AVG(amount) FROM invoices)After =, < or >, the subquery must return a single value. To check against a list, use IN.
SELECT invoice_id, amount
FROM invoices
WHERE customer_id IN (SELECT customer_id FROM customers WHERE region = 'West')Many subqueries can also be written as a JOIN. Use whichever reads closer to the question.
Worked examples
Example 1
Invoices above the average amount.
SELECT customer, amount
FROM invoices
WHERE amount > (SELECT AVG(amount) FROM invoices)The average updates itself when the data changes.
Reading helps, typing makes it stick. Every task gives you a fresh table, and your query is checked by a real database.
Try a taskCommon mistakes
- Using = with a subquery that returns several rows.
- Forgetting the brackets.
- Using NOT IN with a list that contains NULL, which returns nothing.
Where you will use it at work
- Sales: deals bigger than the average deal.
- HR: salaries above the department average.
- Support: tickets slower than average.
Questions people ask
Subquery or JOIN?
Both often work. Use the one that reads closer to the question.
Can a subquery go in SELECT?
Yes, if it returns one value per row.
Are subqueries slow?
Modern databases usually optimise them well.
Ready to write it yourself?
Practice Subqueries