13. Subqueries: a statement inside a statement

Use one SELECT's result as part of another: products dearer than the average, customers who have bought.

A subquery with one value

In chapter 9, "products dearer than the average" ended in an error: avg() can't go in WHERE. The way round is two questions: what is the average price, and which products cost more than that? The first can be written as a SELECT in brackets, right inside the second:

SELECT name, price
FROM product
WHERE price > (SELECT avg(price) FROM product)
ORDER BY price;
nameprice
Banana Bread60.0
Dried Mango90.0
Cheesecake120.0
Cashew Nuts150.0
4 rows

The SELECT in brackets is a subquery. The database works it out first, 57.5, and uses that as if we had typed WHERE price > 57.5 ourselves: 4 products.

A subquery like this gives one value (one row, one column): a scalar subquery. It can go wherever a value can, SELECT included:

SELECT name, price,
       price - (SELECT avg(price) FROM product) AS above_average
FROM product
ORDER BY above_average DESC
LIMIT 3;
namepriceabove_average
Cashew Nuts150.092.5
Cheesecake120.062.5
Dried Mango90.032.5
3 rows

One more good thing: when prices change, this statement is still right, since it works out the average afresh every time instead of keeping the number 57.5.

IN (SELECT ...)

Chapter 4 used IN (1, 2, 3) with a list typed in. A subquery giving several rows of one column can stand in for the list. The products in Snacks, without knowing that category's number:

SELECT name, price
FROM product
WHERE category_id IN (SELECT id FROM category WHERE name = 'Snacks');
nameprice
Potato Chips25.0
Dried Mango90.0
Cashew Nuts150.0
3 rows

The customers who ordered in November 2026:

SELECT id, name, city
FROM customer
WHERE id IN (SELECT customer_id FROM orders WHERE ordered >= '2026-11-01')
ORDER BY id;
idnamecity
3Anan WongsaBangkok
4Pim ChaiyaPhuket
6Kanya BoonmeeChiang Mai
7Wichai SaelimBangkok
8Siriporn KaewdeePhuket
5 rows

5 customers. Even one with several orders that month appears once, because IN only asks "is it in the list?". A JOIN would repeat the row for every order.

EXISTS and NOT EXISTS

EXISTS (SELECT ...) is true when the subquery gives at least one row, whatever is in it. The customers who have ever ordered stationery (category_id = 4):

SELECT c.id, c.name
FROM customer c
WHERE EXISTS (
  SELECT 1
  FROM orders o
  JOIN order_item i ON i.order_id = o.id
  JOIN product p ON p.id = i.product_id
  WHERE o.customer_id = c.id AND p.category_id = 4
)
ORDER BY c.id;
idname
3Anan Wongsa
6Kanya Boonmee
7Wichai Saelim
3 rows

3 customers. The subquery uses c.id, a column of the statement outside it, so the database works the subquery out again for each customer ("has this one ordered stationery?"). SELECT 1 is the custom: EXISTS doesn't look at values, only at whether there is a row.

NOT EXISTS is the other way round. The products that never sold (the same result as LEFT JOIN ... IS NULL in chapter 12):

SELECT id, name
FROM product p
WHERE NOT EXISTS (SELECT 1 FROM order_item i WHERE i.product_id = p.id);
idname
12Highlighter
1 row

Correlated subqueries: a subquery that looks at the outer row

A subquery that uses a column of the outer statement (like c.id above) is a correlated subquery. It is worked out again for every row, so it answers "compared with its own group" questions: the products dearer than the average of their own category:

SELECT p.name, p.category_id, p.price
FROM product p
WHERE p.price > (SELECT avg(x.price) FROM product x WHERE x.category_id = p.category_id)
ORDER BY p.category_id, p.price;
namecategory_idprice
Coffee155.0
Cheesecake2120.0
Dried Mango390.0
Cashew Nuts3150.0
Highlighter425.0
Notebook430.0
6 rows

product is used twice, so each use gets its own short name (p outside, x inside). For each product, the subquery works out the average of that product's category; 6 products pass. Notebook at 30 baht is dearer than the stationery average (23.33), though cheaper than the shop's average.

A correlated subquery can go in SELECT too. The number of orders of each customer:

SELECT c.name,
       (SELECT count(*) FROM orders o WHERE o.customer_id = c.id) AS orders
FROM customer c
ORDER BY orders DESC, c.name;
nameorders
Somchai Jaidee3
Anan Wongsa2
Kanya Boonmee2
Malee Srisuk2
Pim Chaiya2
Wichai Saelim2
Narin Thongdee1
Siriporn Kaewdee1
Lalita Meesuk0
Tawan Rungruang0
10 rows

All 10 customers; those who never ordered get exactly 0 (no count(*) trap as in chapter 12, since the subquery counts real rows of orders).

A correlated subquery reads well, but it is worked out again for every row, which can be slow on big tables. When it can be written as a JOIN with GROUP BY, that is often faster. Chapter 34 comes back to speed.

A subquery in FROM

A SELECT's result is a table too, so it can go after FROM: a derived table, which needs a short name. It helps when you sum up in two steps. "The average order value" needs each order's total first, then the average of those:

SELECT count(*) AS orders, round(avg(total), 2) AS average_order, max(total) AS biggest
FROM (
  SELECT order_id, sum(qty * price) AS total
  FROM order_item
  GROUP BY order_id
) AS t;
ordersaverage_orderbiggest
15229.33490.0
1 row

15 orders, 229.33 baht on average, the biggest 490 baht. Aggregates can't be nested directly, as in avg(sum(...)): you need a subquery like this (or WITH, in chapter 26, which reads more easily).

The NOT IN and NULL trap

NOT IN (SELECT ...) looks like it could stand in for NOT EXISTS, but if the subquery has even one NULL in it, the result is quietly wrong. Add a new category with no products yet, and look for categories with no products:

INSERT INTO category (id, name) VALUES (5, 'Gifts');
SELECT name FROM category WHERE id NOT IN (SELECT category_id FROM product);
name
Gifts
1 row

Gifts, rightly. Now add a product whose category was forgotten (category_id is NULL):

INSERT INTO product (id, name, price, stock) VALUES (13, 'Gift Card', 100, 50);
SELECT name FROM category WHERE id NOT IN (SELECT category_id FROM product);
name
no rows

No rows at all, though Gifts still has no products. 5 NOT IN (1, 2, 3, 4, NULL) means 5 <> 1 AND ... AND 5 <> NULL, and 5 <> NULL is NULL (unknown), so the whole thing is never true.

NOT EXISTS doesn't fall into this trap:

SELECT name FROM category c
WHERE NOT EXISTS (SELECT 1 FROM product p WHERE p.category_id = c.id);
name
Gifts
1 row

Make NOT EXISTS your habit instead of NOT IN (SELECT ...). If you do use NOT IN, always put WHERE column IS NOT NULL in the subquery. IN (without NOT) has no such problem.

  1. Which customers ordered in October 2026 (with IN)?
  2. Which orders total more than the average order (a subquery in FROM, inside a one-value subquery)?
  3. Show every category's name with its number of products, using a correlated subquery in SELECT.
Show the answer
SELECT id, name FROM customer WHERE id IN (SELECT customer_id FROM orders WHERE ordered BETWEEN '2026-10-01' AND '2026-10-31') ORDER BY id;
SELECT order_id, sum(qty * price) AS total FROM order_item GROUP BY order_id HAVING total > (SELECT avg(t) FROM (SELECT sum(qty * price) AS t FROM order_item GROUP BY order_id)) ORDER BY total DESC, order_id;
SELECT c.name, (SELECT count(*) FROM product p WHERE p.category_id = c.id) AS products FROM category c ORDER BY c.id;
idname
1Somchai Jaidee
2Malee Srisuk
4Pim Chaiya
5Narin Thongdee
6Kanya Boonmee
7Wichai Saelim
6 rows
order_idtotal
9490.0
8390.0
15375.0
4300.0
11300.0
6290.0
7235.0
7 rows
nameproducts
Drinks3
Bakery3
Snacks3
Stationery3
Gifts0
5 rows

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made