Sub topic 1
Starting point: nested subqueries and why they get hard to read
A subquery is a SELECT written inside another SQL statement. Subqueries are the tool you reach for before you know about common table expressions (CTEs), and they are still everywhere in production SQL. This chapter shows the four common forms, builds one query that nests three levels deep, and lists the specific ways such queries become hard to read, debug and maintain. The rest of the tutorial introduces the WITH clause as the fix, so this chapter sets up the problem it solves.
Prerequisites
This chapter assumes you can already do the following:
- Write
SELECTqueries withWHEREandORDER BY. - Join two tables with
JOIN ... ON. - Use
GROUP BYwith aggregates such asSUM,COUNTandAVG. - Run SQL in a database of your choice. The examples use standard SQL and run on PostgreSQL, MySQL 8 and SQLite unless noted.
You do not need prior experience with subqueries. The chapter introduces them.
The sample data
All examples use two small tables. Create them once and the queries below will return the results stated in the text.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER,
amount NUMERIC(10, 2) NOT NULL,
order_date DATE NOT NULL
);
INSERT INTO customers (id, name) VALUES
(1, 'Ada'), (2, 'Ben'), (3, 'Cara'), (4, 'Dev');
INSERT INTO orders (id, customer_id, amount, order_date) VALUES
(1, 1, 600.00, '2026-01-05'),
(2, 1, 700.00, '2026-02-10'),
(3, 2, 200.00, '2026-01-20'),
(4, 2, 150.00, '2026-03-02'),
(5, 3, 1500.00, '2026-02-14');Per-customer totals are Ada 1300, Ben 350 and Cara 1500. Dev has no orders. The average of the three customer totals is 1050.
The working model: a subquery is a value, a list, or a table
A subquery returns a result, and where you place it decides what shape of result the database expects. Keeping this rule in mind explains most subquery errors.
| Position | Shape expected | Example form |
|---|---|---|
| `SELECT` list or comparison | One row, one column (a scalar) | `amount > (SELECT AVG(amount) ...)` |
| Right side of `IN` | One column, any number of rows | `id IN (SELECT customer_id ...)` |
| `EXISTS` | Any shape, only row existence matters | `EXISTS (SELECT 1 ...)` |
| `FROM` clause | A full table, with an alias | `FROM (SELECT ...) AS t` |
Scalar subqueries
A scalar subquery returns exactly one value, so you can use it anywhere a single value fits. This query finds orders larger than the overall average order, which is 630.
SELECT id, amount
FROM orders
WHERE amount > (SELECT AVG(amount) FROM orders);It returns orders 2 (700.00) and 5 (1500.00). The inner query runs independently of the outer one. The database can compute the average once and reuse it.
Subqueries with IN and EXISTS
An IN subquery produces a list of values to test membership against. This query finds customers who ordered in February 2026.
SELECT name
FROM customers
WHERE id IN (
SELECT customer_id
FROM orders
WHERE order_date >= DATE '2026-02-01'
AND order_date < DATE '2026-03-01'
);It returns Ada and Cara. EXISTS asks a yes-or-no question instead. It is usually correlated, which the next section explains.
Correlated subqueries
A correlated subquery refers to a column of the outer query. Because of that reference, it cannot be evaluated once. Conceptually, the database evaluates it for each outer row. This query finds orders that are larger than the same customer's own average order.
SELECT o.id, o.customer_id, o.amount
FROM orders o
WHERE o.amount > (
SELECT AVG(o2.amount)
FROM orders o2
WHERE o2.customer_id = o.customer_id
);It returns orders 2 (Ada, 700.00 against an average of 650.00) and 3 (Ben, 200.00 against 175.00). Cara has one order, which equals her average, so it is not returned.
Modern optimizers often rewrite correlated subqueries into joins, so the "once per row" model describes the meaning of the query. It does not necessarily describe how fast it runs.
Derived tables
A derived table is a subquery in the FROM clause. It behaves like a temporary table that exists only for that statement. Most engines require an alias on it.
SELECT t.customer_id, t.total
FROM (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
) AS t
WHERE t.total > 1000;Derived tables matter most for this tutorial. They let you aggregate first and filter or join the aggregate afterwards, and a CTE is essentially a named, reusable form of one.
When nesting gets out of hand
Real questions combine these forms. Suppose you want each customer whose total spend is above the average customer total, along with their order count. You need per-customer totals twice: once to show them, and once to compute their average. With subqueries only, it looks like this.
SELECT c.name, t.total, t.order_count
FROM customers c
JOIN (
SELECT customer_id,
SUM(amount) AS total,
COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
) t ON t.customer_id = c.id
WHERE t.total > (
SELECT AVG(total)
FROM (
SELECT SUM(amount) AS total
FROM orders
GROUP BY customer_id
) AS per_customer
)
ORDER BY t.total DESC;The result is Cara (1500.00, 1 order) and Ada (1300.00, 2 orders). The query is correct, and it is already hard to read. The diagram shows its structure.
Why this is hard to read and maintain
You read it inside out
The logic that runs first (the per-customer aggregation) sits in the middle of the text. The final output columns sit at the top. To understand the query you must jump to the innermost block, work back outwards, and keep each intermediate result in your head.
The same logic appears twice
The per-customer total is written in t and again in per_customer. If the business rule changes, for example to exclude cancelled orders, you must edit both places. If you edit only one, the "above average" comparison silently uses a different definition of total than the one displayed. Nothing raises an error. The numbers are simply inconsistent.
You cannot run a piece on its own
To check what t returns, you must copy the block out, remove the surrounding text, and often fix the indentation and the alias. Debugging a nested query means repeated cut-and-paste. Correlated subqueries are worse, because they reference an outer alias and fail outright when run alone.
Names have no meaning
t and per_customer are aliases that you invent to satisfy the syntax. Neither one describes the business concept. A reader sees FROM (...) t and has to read the whole block to learn what t holds.
Depth multiplies the effort
Each extra level of nesting adds indentation and one more place where a parenthesis can be misplaced. A four-level query is not twice as hard as a two-level one. The reader has to hold more partial results in mind at once.
Common errors with subqueries
These are the mistakes you are most likely to meet before adopting CTEs. Several of them survive the move to CTEs, so it pays to recognize them now.
A scalar subquery returns more than one row
This query expects one amount per customer, but Ada has two orders.
SELECT name,
(SELECT amount FROM orders o WHERE o.customer_id = c.id) AS amount
FROM customers c;PostgreSQL reports more than one row returned by a subquery used as an expression, and other engines give a similar error. The error appears only when the data contains such a case. A query that worked last month can fail after new rows arrive. Aggregate the subquery (SUM, MAX) or restructure the query as a join.
A missing alias on a derived table
SELECT * FROM (SELECT customer_id FROM orders);PostgreSQL (before version 16) and MySQL reject this. PostgreSQL says subquery in FROM must have an alias, and MySQL says Every derived table must have its own alias. Add AS name after the closing parenthesis. Newer PostgreSQL versions relax this rule, but writing the alias keeps the code portable.
NOT IN and NULL
NOT IN compares against every value in the list. If the list contains a NULL, the comparison result is unknown for every row, and the query returns nothing. This minimal case shows it.
SELECT 'row returned' AS result
WHERE 1 NOT IN (SELECT 2 UNION ALL SELECT NULL);This returns zero rows, although 1 is clearly not in the list. In a real schema, one order with a NULL customer_id makes WHERE id NOT IN (SELECT customer_id FROM orders) return no customers at all. Use NOT EXISTS, which does not have this problem. This query finds customers with no orders, which is Dev.
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
SELECT 1
FROM orders o
WHERE o.customer_id = c.id
);A correlated reference binds to the wrong table
Inside a subquery, an unqualified column name is resolved against the subquery's own tables first, then outward. If you forget the alias on one side, the name can bind to the inner table and turn your correlation into a comparison of a column with itself.
-- Wrong: both sides of the comparison refer to the inner orders table
SELECT o.id
FROM orders o
WHERE o.amount > (
SELECT AVG(amount) FROM orders WHERE customer_id = customer_id
);Here customer_id = customer_id is true for every non-null row. The subquery computes the global average, and the query silently returns the wrong rows. Always alias both tables and qualify every column in a correlated subquery, as in the earlier correlated example.
Aggregates in WHERE
You cannot write WHERE SUM(amount) > 1000. WHERE filters rows before grouping, so aggregates are not available there. Use HAVING, or compute the aggregate in a derived table and filter on it, as shown in the derived-table example.
What you need from this chapter
The next chapter takes the last query in this chapter and rewrites it so each intermediate result has a name, is defined once, and appears in reading order. Before that, check that you can do the following:
- Say which shape (scalar, list, table) each subquery position expects.
- Explain what makes a subquery correlated.
- Explain why the per-customer total in the nested example is a maintenance risk.
- Recognize the five errors above on sight.
Exercise
A teammate writes SELECT name FROM customers WHERE id NOT IN (SELECT customer_id FROM orders). It returns the expected row today. Next week, an import inserts an order whose customer_id is NULL. What does the query return then, and how do you rewrite it so it keeps working?
Show answer
It returns no rows. With a NULL in the list, id NOT IN (...) evaluates to unknown for every customer, and unknown rows are filtered out. Rewrite it with NOT EXISTS: SELECT c.name FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id). NOT EXISTS compares by matching rows, so NULL values in orders.customer_id never match and do not affect the result.
Exercise
Using the sample data and only subqueries, write a query that lists each customer's name and number of orders, for customers whose number of orders is above the average number of orders per customer (counting only customers who have orders). Then name one way the query repeats logic.
Show answer
SELECT c.name, t.ordercount FROM customers c JOIN (SELECT customerid, COUNT() AS ordercount FROM orders GROUP BY customerid) AS t ON t.customerid = c.id WHERE t.ordercount > (SELECT AVG(order_count) FROM (SELECT COUNT() AS ordercount FROM orders GROUP BY customerid) AS percustomer); The average is 5/3, about 1.67, so only Ada (2 orders) and Ben (2 orders) are returned. The `COUNT(*) ... GROUP BY customerid aggregation is written twice, once in t and once in per_customer`, so a change to the counting rule must be made in both places.
Exercise
A query contains FROM (SELECT customer_id, SUM(amount) AS total FROM orders GROUP BY customer_id) and fails on MySQL with an error about derived tables. What is the fix?
Show answer
Add an alias after the closing parenthesis, for example AS t. MySQL requires every derived table to have its own alias. Then refer to its columns as t.total and t.customer_id.