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_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

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_namelast_namesalary
KarenMitchell93600
TomBradley62400
NinaCooper52800

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 returnsTypical placeExample
a single valueWHERE with =, <, >, or the SELECT listprice > (SELECT AVG(price) …)
one column, many valuesWHERE with IN or NOT INcustomer_id IN (SELECT customer_id …)
a whole tableFROM, with an aliasFROM (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_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290
order_items 38 rows, 4 columns
order_idproduct_idquantityunit_price
10011404.79
10013252.79
10016424.9
1002223.49
10021035.49
10031604.69
100311684.9
10033502.59
100443179
100493269
100551449
10061304.79
10067106.99
100782219
100711489.9
10071204.99
100846175
1008253.49
1009101204.99
10092403.19
100992279
1010726.99
1010213.49
1011121129
10111104.99
10113122.79
10126823.9
10121404.69
101391279
101452439
101442179
10151504.79
101511289.9
10161045.49
1017233.49
1017726.99
10181804.79
101861024.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;
categoryavg_price
Electronics209
Furniture319
Printer supplies57.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_idnamecategorypricestock
1Copy paper, 500 sheetsPaper4.99420
2Blue ballpoint pens, 10-packWriting3.49310
3Lever arch file, grayFiling2.79185
4Comfort office chairFurniture18912
5Standing deskFurniture4495
6Black ink cartridgePrinter supplies24.964
7Yellow sticky notes, 12 padsWriting6.990
8Mono laser printer L30Electronics2198
927-inch monitorElectronics27915
10Notebook A5, ruledPaper5.49140
11Black toner XLPrinter supplies89.922
12Cross-cut shredderElectronics1290

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 rowsAlias for a subquery in FROM
MySQLerror 1242 "Subquery returns more than 1 row"required
PostgreSQLerroroptional since version 16
SQL Servererrorrequired
SQLite (these exercises)no error, the first row countsworks 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.

Up next: EXISTS and NOT EXISTS

Does this customer have an order, yes or no? EXISTS asks exactly that, and NOT EXISTS sidesteps the NOT IN and NULL trap. It's the reliable way to find what's missing.

Practice EXISTS

Write to us

Choose language

Select your preferred language