Sub topic 1
Starting Point: Nested Subqueries and Why They Get Hard to Read
Prerequisites
This chapter assumes that you can write basic SELECT queries with WHERE and ORDER BY, join related tables, and group rows with GROUP BY and aggregate functions such as SUM and COUNT. Familiarity with subqueries helps, but the examples explain the important parts.
What a Nested Subquery Is
A subquery is a query written inside another SQL statement. The inner query produces a value or a temporary result that the outer query uses.
For example, suppose orders has these columns:
customer_idamount
You can find customers whose total order value is greater than 1,000 with a derived table. A derived table is a subquery in the FROM clause. It behaves like a table for the duration of the outer query.
SELECT c.name, totals.total_amount
FROM customers AS c
JOIN (
SELECT customer_id, SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id
) AS totals
ON totals.customer_id = c.id
WHERE totals.total_amount > 1000
ORDER BY totals.total_amount DESC;The inner query groups orders by customer and calculates one total per customer. The outer query joins those totals to customers and filters the result.
The alias totals is required by many SQL databases. Without it, the outer query has no name by which to refer to the derived table.
Why Nesting Becomes Difficult
One nested query is often clear. The difficulty grows when each result depends on another result. Consider a report that calculates monthly revenue and then compares each month with the previous month:
SELECT monthly.month_start,
monthly.revenue,
monthly.revenue - (
SELECT previous.revenue
FROM (
SELECT DATE_TRUNC('month', order_date) AS month_start,
SUM(amount) AS revenue
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
) AS previous
WHERE previous.month_start = monthly.month_start - INTERVAL '1 month'
) AS change_from_previous
FROM (
SELECT DATE_TRUNC('month', order_date) AS month_start,
SUM(amount) AS revenue
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
) AS monthly
ORDER BY monthly.month_start;This query may work, but the same monthly aggregation appears twice. That repetition creates several problems:
- A change to the monthly calculation must be made in multiple places.
- Parentheses and aliases make the query harder to scan.
- It is difficult to see the report's logical stages.
- A mistake in one copy can produce inconsistent results.
- Debugging an inner query requires mentally separating it from the outer query.
The query has a useful logical shape, but that shape is hidden inside syntax. First calculate monthly revenue. Then find the previous month's revenue. Finally calculate the difference. A query that expresses those stages by name is easier to review.
Read the Query from the Inside Out
When you encounter a nested query, identify each level before changing it.
- Find the innermost
SELECT. - Determine whether it returns one value, one row, or many rows.
- Check which columns and aliases it exposes.
- Move outward one level at a time.
- Confirm how each outer query uses the inner result.
A subquery in WHERE often returns a value or a set of values. A subquery in FROM returns rows and must have a table alias. A subquery in SELECT is usually expected to return one value for each outer row.
These shapes are not interchangeable. A scalar subquery that returns two rows can cause an error. A subquery used with IN can return multiple rows, but its selected column must match the value being tested.
See the Logical Stages
The monthly report can be pictured as a sequence of transformations:
This staged thinking is the main reason developers introduce a common table expression, or CTE. A CTE names an intermediate result near the start of the statement. Later query logic can refer to that name instead of placing the entire calculation inside parentheses.
The important design question is not whether nesting is allowed. SQL supports it. The question is whether the query communicates its stages clearly and gives each intermediate result a useful name.
When to Refactor
Refactor a nested subquery when:
- The same subquery is repeated.
- More than one transformation is buried inside parentheses.
- You need to inspect an intermediate result while debugging.
- The aliases no longer explain what each result represents.
- The query mixes aggregation, filtering, joining, and comparison in one dense expression.
Keep a nested subquery when it expresses a small, local condition. For example, checking whether an order exceeds the average order value can remain readable:
SELECT order_id, customer_id, amount
FROM orders
WHERE amount > (
SELECT AVG(amount)
FROM orders
);The inner query has one purpose and returns one value. Naming it separately may add structure without adding clarity.
Exercise
What makes a derived table different from an ordinary table in a SQL query?
Show answer
A derived table is a subquery in the FROM clause. It produces rows for the current statement and must be given an alias, but it does not permanently exist as a table.