MySQL Subqueries
A subquery is a SELECT inside another statement, written in parentheses. You've already met a few (IN (SELECT ...), EXISTS (SELECT ...)). This lesson looks at the different kinds and where each one fits.
| Kind | Returns | Used with |
|---|---|---|
| scalar subquery | one value (one row, one column) | anywhere a value fits: =, >, the select list |
| column subquery | one column, many rows | IN, ANY, ALL |
| row subquery | one row, several columns | (a, b) = (SELECT ...) |
| table subquery (derived table) | a whole result | FROM (SELECT ...) AS alias |
Scalar subqueries
"Products more expensive than the average product." The inner query computes one number; the outer one compares with it:
SELECT ROUND(AVG(unit_price), 2) AS avg_price FROM products;
SELECT name, unit_price
FROM products
WHERE unit_price > (SELECT AVG(unit_price) FROM products)
ORDER BY unit_price DESC;+-----------+
| avg_price |
+-----------+
| 5.71 |
+-----------+
+--------------------+------------+
| name | unit_price |
+--------------------+------------+
| Espresso Beans 1kg | 24.50 |
| Chocolate Cake | 18.00 |
| Laundry Pods (30) | 11.90 |
| Aged Gruyere 250g | 7.95 |
| Earl Grey Tea | 6.75 |
+--------------------+------------+
A scalar subquery can also produce a column. Here each employee's salary is compared with the company average:
SELECT first_name, salary,
salary - (SELECT ROUND(AVG(salary), 2) FROM employees) AS vs_average
FROM employees
WHERE employee_id IN (1, 4, 8);+------------+---------+------------+
| first_name | salary | vs_average |
+------------+---------+------------+
| Grace | 9500.00 | 4706.25 |
| Linus | 3900.00 | -893.75 |
| Sara | 2750.00 | -2043.75 |
+------------+---------+------------+
If a scalar subquery returns more than one row, the statement fails with Subquery returns more than 1 row (error 1242). If it returns no rows, its value is NULL.
Correlated subqueries
A correlated subquery refers to a column of the outer query, so its result differs for each outer row. "Each product that costs more than the average of its own category":
SELECT p.name, p.category_id, p.unit_price
FROM products AS p
WHERE p.unit_price > (
SELECT AVG(p2.unit_price)
FROM products AS p2
WHERE p2.category_id = p.category_id
)
ORDER BY p.category_id, p.unit_price DESC;+----------------------+-------------+------------+
| name | category_id | unit_price |
+----------------------+-------------+------------+
| Espresso Beans 1kg | 1 | 24.50 |
| Chocolate Cake | 2 | 18.00 |
| Aged Gruyere 250g | 3 | 7.95 |
| Gala Apples 1kg | 4 | 2.99 |
| Cherry Tomatoes 500g | 4 | 2.75 |
| Roasted Almonds 200g | 5 | 5.49 |
| Laundry Pods (30) | 6 | 11.90 |
+----------------------+-------------+------------+
The inner WHERE p2.category_id = p.category_id ties the subquery to the current outer row. Correlated subqueries in the select list are a readable way to add a count or a "latest" value per row:
SELECT c.first_name,
(SELECT COUNT(*) FROM orders AS o WHERE o.customer_id = c.customer_id) AS orders,
(SELECT MAX(o.order_date) FROM orders AS o WHERE o.customer_id = c.customer_id) AS last_order
FROM customers AS c
WHERE c.customer_id <= 4;+------------+--------+------------+
| first_name | orders | last_order |
+------------+--------+------------+
| Ana | 3 | 2025-04-08 |
| Ben | 3 | 2025-05-20 |
| Chloe | 1 | 2025-03-21 |
| Daniel | 2 | 2025-03-15 |
+------------+--------+------------+
Derived tables: subqueries in FROM
A subquery in FROM acts as a temporary table for the rest of the query. It must have an alias. This is the classic way to aggregate twice, for example "the average order value", where the order totals have to be computed first:
SELECT COUNT(*) AS orders,
ROUND(AVG(t.total), 2) AS avg_order_value,
MAX(t.total) AS biggest_order
FROM (
SELECT order_id, SUM(quantity * unit_price * (1 - discount)) AS total
FROM order_details
GROUP BY order_id
) AS t;+--------+-----------------+---------------+
| orders | avg_order_value | biggest_order |
+--------+-----------------+---------------+
| 22 | 25.27 | 59.0000 |
+--------+-----------------+---------------+
Row subqueries
Compare several columns at once with a row constructor. "Which orders have the same employee and the same status as order 20?":
SELECT order_id, employee_id, order_date
FROM orders
WHERE (employee_id, status) = (SELECT employee_id, status FROM orders WHERE order_id = 20);+----------+-------------+------------+
| order_id | employee_id | order_date |
+----------+-------------+------------+
| 20 | 5 | 2025-05-28 |
| 22 | 5 | 2025-06-03 |
+----------+-------------+------------+
That found every processing order handled by employee 5, including order 20 itself.
Subqueries in UPDATE and DELETE
Subqueries can decide which rows to change, and compute the new values:
UPDATE products
SET discontinued = 1
WHERE product_id NOT IN (SELECT DISTINCT product_id FROM order_details);
SELECT product_id, name, discontinued FROM products WHERE discontinued = 1;+------------+----------------------+--------------+
| product_id | name | discontinued |
+------------+----------------------+--------------+
| 4 | Sparkling Water 6x1L | 1 |
| 8 | Rye Crackers | 1 |
+------------+----------------------+--------------+
Note: MySQL doesn't let you modify a table and select from the same table in a subquery of that statement (error 1093, You can't specify target table ... for update in FROM clause). Wrap the inner query in a derived table (
WHERE id IN (SELECT id FROM (SELECT ...) AS t)) or use a join instead.
Subquery or join?
Many questions can be answered either way. Joins are usually best when you need columns from both tables; IN/EXISTS when you only filter by the other table (they never duplicate rows); derived tables or CTEs (next lessons) when a result needs several steps of aggregation. MySQL's optimizer rewrites many subqueries into joins internally, so choose the clearest form first.
Test yourself
What is a correlated subquery?
- A subquery in FROM
- A subquery that refers to columns of the outer query
- A subquery that returns one value
- A subquery joined with UNION
What does a derived table (subquery in FROM) require in MySQL?
- An ORDER BY
- An alias
- A LIMIT
- An index
What happens when a scalar subquery used with = returns two rows?
- The first row is used
- The statement fails
- Both are compared with OR
- NULL is used