Part 06 / Topic 5 of 8
Derived tables: subqueries in FROM
A subquery can stand where a table stands. Aggregate first, then query the aggregate — "average lifetime spend of customers who have spent anything":
SELECT round(avg(spent), 2) AS avg_lifetime_spend
FROM (
SELECT o.customer_id, sum(oi.quantity * oi.unit_price) AS spent
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.customer_id
) AS customer_totals;
avg_lifetime_spend
--------------------
1245.25
(1 row)
The inner query builds a temporary "table" (customer_totals — the alias is mandatory), the outer one treats it like any other FROM source. This two-step shape — aggregate, then work on the aggregates — is also the clean cure for Part 5's fan-out pitfall: total up order lines per order first, then join the one-row-per-order result onward, and nothing multiplies.
🧪 Quick quiz — answer from memory, then check.
- What must every derived table have that's easy to forget?
- How does a derived table cure join fan-out?
Show the answers
- An alias —
) AS name— Postgres errors without it. - Aggregate to the grain you need (one row per order) inside the subquery, then join that — the multiplying rows are already collapsed.
Exercise 5: Average order value, fan-out-proof
What to do: Compute the average order value by first collapsing order_items to one total per order (a derived table), then averaging. It should match the Stage 1 project's number.
Sample output:
avg_order_value
-----------------
659.00
(1 row)
💡 Hint: FROM ( SELECT order_id, sum(...) ... GROUP BY order_id ) AS per_order — and don't forget the alias.
Show the solution to Exercise 5
-- Exercise 5: Average order value, the fan-out-proof way
-- Aggregate to one row per order first, then average the per-order totals.
SELECT round(avg(order_total), 2) AS avg_order_value
FROM (
SELECT oi.order_id, sum(oi.quantity * oi.unit_price) AS order_total
FROM order_items oi
GROUP BY oi.order_id
) AS per_order;