Sub topic 6
Comparing a Row to an Aggregate of Its Related Rows
Prerequisites
This chapter assumes that you know SELECT, WHERE, INNER JOIN, aggregate functions such as AVG, table aliases, and NULL as a missing value. You should also understand that a subquery is a query nested inside another SQL statement.
A correlated scalar subquery returns one value for each row of the outer query. It is correlated because the inner query refers to a column from the current outer row.
Comparing each order with its customer's average
Suppose orders contains these columns:
order_id: identifies an ordercustomer_id: identifies the customertotal: the order amount
The following query finds orders whose total is greater than that customer's average order total:
SELECT o.order_id, o.customer_id, o.total
FROM orders o
WHERE o.total > (
SELECT AVG(o2.total)
FROM orders o2
WHERE o2.customer_id = o.customer_id
);The outer query examines one order at a time. For that order, the inner query calculates the average of orders belonging to the same customer.
The condition
o2.customer_id = o.customer_idcreates the correlation. o2 refers to rows inside the inner query. o refers to the current row from the outer query.
For an order belonging to customer 42, the database evaluates the inner query as though it contained a condition for customer 42. It then compares the current order's total with that result. The process repeats for the next outer order.
Scalar subqueries must return one value
A scalar subquery is used where SQL expects a single value. AVG, MIN, MAX, and SUM normally produce one value for the rows they receive, so they often work well in this pattern.
For example, this query finds each customer's most recent order date:
SELECT c.customer_id, c.name,
(SELECT MAX(o.order_date)
FROM orders o
WHERE o.customer_id = c.customer_id) AS last_order_date
FROM customers c;The inner query is evaluated once for each customer. If a customer has no orders, MAX has no input rows and returns NULL. The customer still appears in the result, but last_order_date is NULL.
An aggregate does not always protect a scalar subquery. A subquery that selects an ordinary column can return multiple rows, which causes an error in a scalar position:
-- This can fail if a customer has multiple orders.
SELECT c.customer_id,
(SELECT o.total
FROM orders o
WHERE o.customer_id = c.customer_id) AS some_total
FROM customers c;Use an aggregate when you need one summary value, or use a different query shape when you need multiple related rows.
`NULL` and comparisons
If the inner aggregate returns NULL, a comparison such as
o.total > NULLdoes not evaluate to true. It evaluates to UNKNOWN, so the row is removed by the WHERE clause.
This matters for customers with no related orders and for aggregates such as AVG over rows whose value is NULL. If those rows should be handled explicitly, add a condition or use COALESCE with a carefully chosen default:
SELECT c.customer_id, c.name
FROM customers c
WHERE COALESCE((
SELECT AVG(o.total)
FROM orders o
WHERE o.customer_id = c.customer_id
), 0) = 0;Only use COALESCE when treating “no value” as zero matches the business rule. An unknown average and an average of zero can mean different things.
A grouped alternative
You can calculate averages once and join them to the orders:
SELECT o.order_id, o.customer_id, o.total
FROM orders o
JOIN (
SELECT customer_id, AVG(total) AS average_total
FROM orders
GROUP BY customer_id
) a ON a.customer_id = o.customer_id
WHERE o.total > a.average_total;The correlated form reads naturally when the question is “compare this row with its related rows.” The grouped form can be easier to extend when you need several aggregates or want to inspect the intermediate averages. The query planner may transform either form into a similar execution plan.
Exercise
Write a query that returns each customer's orders whose total is below that customer's maximum order total.
Show answer
SELECT o.order_id, o.customer_id, o.total FROM orders o WHERE o.total < (SELECT MAX(o2.total) FROM orders o2 WHERE o2.customer_id = o.customer_id);