SQL subquery: a query inside a query
Which products cost more than average? First you need the average, then the products. A subquery, also called a nested query, does both steps at once: the inner query works out the number, the outer query uses it to filter.
In short: WHERE price > (SELECT AVG(price) FROM products) compares every price with the average returned by the subquery in parentheses. A subquery is always wrapped in parentheses and can sit in WHERE, in FROM or in the SELECT list.
What you should know first: AVG, MIN and MAX, IN and GROUP BY.
Try it now
SELECT AVG(price) FROM products gives you the average price. Now drop that whole query into the spot where you'd normally type a number.
Task Sales wants the products that cost more than the average price of all products. Show name and price. Let the database work out the average itself, so the list stays right after the next price change.
products 12 rows, 5 columns
| product_id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Copy paper, 500 sheets | Paper | 4.99 | 420 |
| 2 | Blue ballpoint pens, 10-pack | Writing | 3.49 | 310 |
| 3 | Lever arch file, gray | Filing | 2.79 | 185 |
| 4 | Comfort office chair | Furniture | 189 | 12 |
| 5 | Standing desk | Furniture | 449 | 5 |
| 6 | Black ink cartridge | Printer supplies | 24.9 | 64 |
| 7 | Yellow sticky notes, 12 pads | Writing | 6.99 | 0 |
| 8 | Mono laser printer L30 | Electronics | 219 | 8 |
| 9 | 27-inch monitor | Electronics | 279 | 15 |
| 10 | Notebook A5, ruled | Paper | 5.49 | 140 |
| 11 | Black toner XL | Printer supplies | 89.9 | 22 |
| 12 | Cross-cut shredder | Electronics | 129 | 0 |
How a subquery works
The database evaluates the part in parentheses first and plugs the result into the outer query. Here's who earns more than the average salary:
SELECT first_name, last_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
| first_name | last_name | salary |
|---|---|---|
| Karen | Mitchell | 93600 |
| Tom | Bradley | 62400 |
| Nina | Cooper | 52800 |
The subquery returns 51266.67, the average of the nine salaries on file (Laura Hughes has no salary yet, and AVG skips the empty value). Unlike a number typed into the query, this keeps working when someone gets a raise.
Where a subquery goes depends on what it returns:
| The subquery returns | Typical place | Example |
|---|---|---|
| a single value | WHERE with =, <, >, or the SELECT list | price > (SELECT AVG(price) …) |
| one column, many values | WHERE with IN or NOT IN | customer_id IN (SELECT customer_id …) |
| a whole table | FROM, with an alias | FROM (SELECT …) AS c |
In the SELECT list, a subquery feeds into every row: SELECT name, price, ROUND(price - (SELECT AVG(price) FROM products), 2) AS diff FROM products WHERE category = 'Electronics' shows the monitor sits 162.04 above the average and the shredder only 12.04.
One more exercise: subquery with IN
When the subquery returns a whole list, compare with IN. For each row the database asks: is this value on the list?
Task Purchasing wants to offer volume discounts and asks: which products have ever been ordered in large quantities? Show name and category of every product that appears in at least one order line with a quantity of 10 or more, each product only once. Use a subquery with IN.
products 12 rows, 5 columns
| product_id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Copy paper, 500 sheets | Paper | 4.99 | 420 |
| 2 | Blue ballpoint pens, 10-pack | Writing | 3.49 | 310 |
| 3 | Lever arch file, gray | Filing | 2.79 | 185 |
| 4 | Comfort office chair | Furniture | 189 | 12 |
| 5 | Standing desk | Furniture | 449 | 5 |
| 6 | Black ink cartridge | Printer supplies | 24.9 | 64 |
| 7 | Yellow sticky notes, 12 pads | Writing | 6.99 | 0 |
| 8 | Mono laser printer L30 | Electronics | 219 | 8 |
| 9 | 27-inch monitor | Electronics | 279 | 15 |
| 10 | Notebook A5, ruled | Paper | 5.49 | 140 |
| 11 | Black toner XL | Printer supplies | 89.9 | 22 |
| 12 | Cross-cut shredder | Electronics | 129 | 0 |
order_items 38 rows, 4 columns
| order_id | product_id | quantity | unit_price |
|---|---|---|---|
| 1001 | 1 | 40 | 4.79 |
| 1001 | 3 | 25 | 2.79 |
| 1001 | 6 | 4 | 24.9 |
| 1002 | 2 | 2 | 3.49 |
| 1002 | 10 | 3 | 5.49 |
| 1003 | 1 | 60 | 4.69 |
| 1003 | 11 | 6 | 84.9 |
| 1003 | 3 | 50 | 2.59 |
| 1004 | 4 | 3 | 179 |
| 1004 | 9 | 3 | 269 |
| 1005 | 5 | 1 | 449 |
| 1006 | 1 | 30 | 4.79 |
| 1006 | 7 | 10 | 6.99 |
| 1007 | 8 | 2 | 219 |
| 1007 | 11 | 4 | 89.9 |
| 1007 | 1 | 20 | 4.99 |
| 1008 | 4 | 6 | 175 |
| 1008 | 2 | 5 | 3.49 |
| 1009 | 10 | 120 | 4.99 |
| 1009 | 2 | 40 | 3.19 |
| 1009 | 9 | 2 | 279 |
| 1010 | 7 | 2 | 6.99 |
| 1010 | 2 | 1 | 3.49 |
| 1011 | 12 | 1 | 129 |
| 1011 | 1 | 10 | 4.99 |
| 1011 | 3 | 12 | 2.79 |
| 1012 | 6 | 8 | 23.9 |
| 1012 | 1 | 40 | 4.69 |
| 1013 | 9 | 1 | 279 |
| 1014 | 5 | 2 | 439 |
| 1014 | 4 | 2 | 179 |
| 1015 | 1 | 50 | 4.79 |
| 1015 | 11 | 2 | 89.9 |
| 1016 | 10 | 4 | 5.49 |
| 1017 | 2 | 3 | 3.49 |
| 1017 | 7 | 2 | 6.99 |
| 1018 | 1 | 80 | 4.79 |
| 1018 | 6 | 10 | 24.9 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Subquery in FROM: the derived table
A subquery can also return a whole table that you use after FROM just like a real one. That lets you filter a grouped result without HAVING. Which categories have an average price above 50?
SELECT category, ROUND(avg_price, 2) AS avg_price
FROM (SELECT category, AVG(price) AS avg_price
FROM products
GROUP BY category) AS c
WHERE avg_price > 50;
| category | avg_price |
|---|---|
| Electronics | 209 |
| Furniture | 319 |
| Printer supplies | 57.4 |
The derived table gets an alias, c in this case. MySQL and SQL Server insist on it; PostgreSQL has made it optional since version 16 (more below). Once these in-between tables grow, WITH (level 5) keeps them readable.
Correlated subquery: once per row
So far the subquery ran once and produced a fixed value. A correlated subquery refers to the row the outer query is currently looking at, so it runs again for every row. That's how you compare each product with the average of its own category.
Task Purchasing is reviewing prices by product group. Find the products that cost more than the average price of their own category, so a chair is compared with furniture and a pen with writing supplies. Show name, category and price.
products 12 rows, 5 columns
| product_id | name | category | price | stock |
|---|---|---|---|---|
| 1 | Copy paper, 500 sheets | Paper | 4.99 | 420 |
| 2 | Blue ballpoint pens, 10-pack | Writing | 3.49 | 310 |
| 3 | Lever arch file, gray | Filing | 2.79 | 185 |
| 4 | Comfort office chair | Furniture | 189 | 12 |
| 5 | Standing desk | Furniture | 449 | 5 |
| 6 | Black ink cartridge | Printer supplies | 24.9 | 64 |
| 7 | Yellow sticky notes, 12 pads | Writing | 6.99 | 0 |
| 8 | Mono laser printer L30 | Electronics | 219 | 8 |
| 9 | 27-inch monitor | Electronics | 279 | 15 |
| 10 | Notebook A5, ruled | Paper | 5.49 | 140 |
| 11 | Black toner XL | Printer supplies | 89.9 | 22 |
| 12 | Cross-cut shredder | Electronics | 129 | 0 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Common mistakes
AVG straight in WHERE
WHERE price > AVG(price) fails because WHERE checks one row at a time and AVG needs many. The exercise replies "COUNT, SUM or AVG cannot go directly in WHERE" and shows you the way out: a subquery in parentheses.
Too many columns in the subquery
product_id IN (SELECT * FROM order_items …) fails because IN needs exactly one column. The exercise says "The subquery returns 4 columns, only one is allowed here". Select only the column you're comparing.
= instead of IN
product_id = (SELECT product_id FROM order_items …) looks fine, but = compares with a single value. SQLite quietly takes the first value on the list, so the exercise reports "Your query returns only 1 row". Other databases stop with an error. With several values, you want IN.
NOT IN and NULL
If the subquery returns even a single NULL, NOT IN finds no rows at all, and no error tells you why. Whether a value differs from NULL is unknown (NULL in SQL). You'll walk into this trap on purpose in the next lesson and get around it with NOT EXISTS.
JOIN instead of IN
Joining products to order_items gives one row per matching order line. Copy paper, with eight large order lines, shows up eight times: "Your query returns 15 rows. Wanted: 6 rows." IN just asks yes or no and lists each product once.
Missing link in a correlated subquery
WHERE category = category inside the subquery compares the inner column with itself, which is always true. You're back to the average of all products, and the exercise reports one row too few. Give the outer table an alias and write category = p.category.
Subqueries in MySQL, PostgreSQL, SQL Server and SQLite
All four handle subqueries in WHERE, FROM and the SELECT list. The details differ:
| Database | = with a subquery that returns several rows | Alias for a subquery in FROM |
|---|---|---|
| MySQL | error 1242 "Subquery returns more than 1 row" | required |
| PostgreSQL | error | optional since version 16 |
| SQL Server | error | required |
| SQLite (these exercises) | no error, the first row counts | works without one in the exercises |
Use the alias anyway and your query runs everywhere. One MySQL quirk: it rejects LIMIT inside a subquery used with IN, ALL, ANY or SOME, with error 1235.
FAQ
What is a subquery in SQL?
A SELECT in parentheses inside another query, also called a nested query or inner query. The outer query uses its result as a single value, a list or a table.
Subquery or JOIN?
If you need columns from both tables in the result, use a JOIN. If you only want to know whether matching rows exist, IN or EXISTS is often clearer and never duplicates rows. Plenty of tasks can be solved either way.
How deep can I nest queries?
A subquery can contain subqueries of its own. SQL Server documents a limit of 32 levels. In practice, readability suffers from the second level onward, and WITH is the better tool.
How do I spot a correlated subquery?
It uses a column from the outer query, usually through the outer alias, as in p.category. A quick test: if the subquery runs on its own, it isn't correlated. If it complains about a missing column, it depends on the outer query.