TExcelTAD
Home › SQL › SQL Subqueries

SQL Subqueries

A subquery is a SELECT nested inside another statement, written in parentheses. The outer query uses its result as a value, a list or a table. You have already met a few; this lesson puts them in order.

Kind Returns Used with
Scalar subquery one value (1 row, 1 column) =, <, >, in the SELECT list
List subquery one column, many rows IN, NOT IN
Table subquery (derived table) rows and columns FROM (…) AS alias, joins
Correlated subquery depends on the outer row EXISTS, SELECT list, WHERE

Scalar subqueries

A subquery that returns exactly one value can stand wherever a value can. Products that cost more than twice the average price, with the average shown:

sql · try it yourself
SELECT name, price,
       (SELECT ROUND(AVG(price), 2) FROM products) AS overall_avg
FROM products
WHERE price > (SELECT AVG(price) FROM products) * 2
ORDER BY price DESC;
name                        | price | overall_avg
----------------------------+-------+------------
Noise-Cancelling Headphones | 149   | 22.53
Mechanical Keyboard         | 89    | 22.53
Coffee Grinder              | 59.9  | 22.53
(3 rows)

List subqueries with IN

Customers who bought anything from the Books category:

sql · try it yourself
SELECT name, country
FROM customers
WHERE customer_id IN (
  SELECT o.customer_id
  FROM orders AS o
  JOIN order_items AS oi ON oi.order_id = o.order_id
  JOIN products AS p ON p.product_id = oi.product_id
  WHERE p.category_id = 8
)
ORDER BY name;
name          | country
--------------+---------
Arjun Sharma  | Norway
Code & Coffee | Japan
Corner Cafe   | Germany
Elif Yilmaz   | Canada
Green Fork    | Canada
Jonas Garcia  | UK
Lena Andersen | Portugal
Omar Murphy   | India
Tech Nest     | USA
(9 rows)

Derived tables in FROM

A subquery in FROM acts as a temporary table — it must have an alias. Here we first compute each order's total, then summarise those totals per status:

sql · try it yourself
SELECT o.status,
       COUNT(*) AS orders,
       ROUND(AVG(t.total), 2) AS avg_order_value
FROM (
  SELECT oi.order_id, SUM(oi.quantity * p.price) AS total
  FROM order_items AS oi
  JOIN products AS p ON p.product_id = oi.product_id
  GROUP BY oi.order_id
) AS t
JOIN orders AS o ON o.order_id = t.order_id
GROUP BY o.status
ORDER BY avg_order_value DESC;
status     | orders | avg_order_value
-----------+--------+----------------
delivered  | 16     | 150.35
shipped    | 9      | 149.57
cancelled  | 7      | 135.96
processing | 8      | 60.12
(4 rows)

Aggregating twice ("average of sums") always needs this two-step shape.

Correlated subqueries

A correlated subquery refers to the outer query's current row, so it is evaluated once per row. Products that are the most expensive in their own category:

sql · try it yourself
SELECT p.name, p.category_id, p.price
FROM products AS p
WHERE p.price = (
  SELECT MAX(p2.price)
  FROM products AS p2
  WHERE p2.category_id = p.category_id
)
ORDER BY p.category_id;
name                        | category_id | price
----------------------------+-------------+------
Espresso Beans              | 1           | 24.5
Chocolate Cake              | 2           | 22
Swiss Cheese                | 3           | 7.8
Avocados                    | 4           | 4.5
Salted Almonds              | 5           | 5.99
Noise-Cancelling Headphones | 6           | 149
Coffee Grinder              | 7           | 59.9
Learn Rust in Practice      | 8           | 39
(8 rows)

The inner query uses p.category_id from the outer row — that is the correlation.

A correlated subquery in the SELECT list adds a computed column per row — the number of orders of each customer:

sql · try it yourself
SELECT c.name,
       (SELECT COUNT(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS orders,
       (SELECT MAX(order_date) FROM orders AS o WHERE o.customer_id = c.customer_id) AS last_order
FROM customers AS c
WHERE c.country IN ('France', 'Canada')
ORDER BY orders DESC, c.name;
name         | orders | last_order
-------------+--------+-----------
Bright Bytes | 4      | 2025-09-11
Kai Moreau   | 4      | 2025-10-09
Green Fork   | 2      | 2025-04-04
Elif Yilmaz  | 1      | 2025-04-23
(4 rows)

Subquery errors

A scalar subquery must return at most one row. SQLite quietly uses the first row; PostgreSQL, MySQL and SQL Server raise an error such as "subquery returns more than one row". Make sure scalar subqueries are aggregates or filter on a unique key.

Tip: When a subquery grows large or is used twice, a common table expression (WITH …, next lesson) makes the query much easier to read.

Test yourself

What is a correlated subquery?

  1. A subquery in FROM
  2. A subquery that refers to columns of the outer query
  3. A subquery that returns one value
  4. A subquery with a JOIN

What must a subquery in FROM have in most databases?

  1. An ORDER BY
  2. An alias
  3. A GROUP BY
  4. A LIMIT

How do you compute the average of per-order totals?

  1. AVG(SUM(x))
  2. SUM(AVG(x))
  3. Sum per order in a subquery, then AVG in the outer query
  4. It is impossible