Sub topic 6
Comparing a Row to an Aggregate of Its Related Rows
This chapter assumes you can write SELECT and WHERE clauses, use aliases, and use aggregates such as AVG, MAX, and COUNT. It also assumes you know that NULL means a missing value. You should have read the earlier chapters on correlated subqueries and EXISTS. The chapter shows how a correlated subquery can return a single computed value, such as an average or a latest date, for each outer row.
The idea: a per-row aggregate
EXISTS asks a yes-or-no question about related rows. Often you need a number instead: "How does this order compare with this customer's average order?" or "When did this customer last order?"
A correlated scalar subquery answers that. It is a subquery that:
- refers to a column of the outer query, so it is correlated, and
- returns exactly one row with one column, so it is scalar.
Because it returns one value, you can use it anywhere a single value fits. That includes a comparison in WHERE and a column in the SELECT list.
The examples use these tables:
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id),
order_date DATE NOT NULL,
total NUMERIC(10, 2)
);
INSERT INTO customers (customer_id, name) VALUES
(1, 'Ana'), (2, 'Ben'), (3, 'Cy');
INSERT INTO orders (order_id, customer_id, order_date, total) VALUES
(101, 1, DATE '2026-01-05', 50.00),
(102, 1, DATE '2026-02-10', 150.00),
(103, 1, DATE '2026-03-01', 100.00),
(104, 2, DATE '2026-01-20', 80.00),
(105, 2, DATE '2026-02-15', 80.00);Ana has three orders averaging 100. Ben has two orders averaging 80. Cy has no orders.
Aggregate in the WHERE clause
This query returns orders whose total is above the average total of the same customer's orders:
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
);With the sample data, the result is one row: order 102, with a total of 150.00.
The mental model has three steps:
- The database takes one outer row, for example order 101 with customer 1.
- It runs the inner query with
o.customer_idfixed to 1. The inner query averages the totals of all orders for customer 1 and returns 100. - It compares
o.total(50) with 100. The comparison is false, so the row is discarded.
The database repeats this for every outer row. Order 102 passes (150 > 100). Orders 104 and 105 fail, because 80 is not greater than 80.
This describes the logical meaning. The optimizer may compute all averages at once and join them back, as long as the result is the same.
Two aliases for the same table
The inner query reads orders too, so you need two aliases: o for the outer copy and o2 for the inner copy. Without distinct aliases the database cannot tell which copy you mean.
Name resolution has a gotcha. An unqualified column name is looked up in the innermost query first. Consider this bug:
SELECT o.order_id, o.total
FROM orders o
WHERE o.total > (
SELECT AVG(o2.total)
FROM orders o2
WHERE o2.customer_id = customer_id
);The bare customer_id resolves to o2.customer_id, the inner table. The condition becomes o2.customer_id = o2.customer_id, which is true for every non-NULL row. Every order is compared with the average of all orders, and no error appears. Always qualify columns in correlated subqueries.
Aggregate in the SELECT list
A scalar subquery can also produce a column:
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;| customer_id | name | last_order_date |
|---|---|---|
| 1 | Ana | 2026-03-01 |
| 2 | Ben | 2026-02-15 |
| 3 | Cy | NULL |
Cy has no orders, so the inner query finds no rows. MAX over zero rows is NULL, and Cy still appears in the output. This is a useful property: the outer query decides which rows appear, and the subquery only supplies a value. A subquery in the SELECT list never removes outer rows.
What happens when there are no related rows
An aggregate over an empty set depends on the function:
| Aggregate over zero rows | Result |
|---|---|
| COUNT(*) or COUNT(column) | 0 |
| SUM, AVG, MIN, MAX | NULL |
This matters for comparisons. Suppose you want customers with more than two orders:
SELECT c.customer_id, c.name
FROM customers c
WHERE (SELECT COUNT(*)
FROM orders o
WHERE o.customer_id = c.customer_id) > 2;Cy's count is 0, so the comparison is false and Cy is excluded. This returns Ana only.
If you compare with an AVG or MAX instead, Cy's inner result is NULL. A comparison with NULL gives UNKNOWN, and WHERE keeps only rows where the condition is true. The row is discarded as well, but through a different path. This is usually what you want. It becomes a problem if you wanted to keep customers with no orders. In that case, handle the NULL explicitly:
SELECT c.customer_id, c.name
FROM customers c
WHERE COALESCE(
(SELECT MAX(o.total)
FROM orders o
WHERE o.customer_id = c.customer_id), 0) < 100;This treats "no orders" as a maximum of 0, so Cy qualifies. Ben also qualifies, because his maximum is 80. Ana does not, because her maximum is 150.
NULLs inside the aggregated column
Aggregates other than COUNT(*) ignore NULL values in the column. If total can be NULL, two things follow:
AVG(o2.total)averages only the non-NULL totals. Orders with a NULL total are skipped, and they do not count as zero.- An outer row with a NULL
o.totalnever passeso.total > (...), because the comparison is UNKNOWN.
If a missing total should count as 0, say so in the query: AVG(COALESCE(o2.total, 0)) for the inner side, and COALESCE(o.total, 0) for the outer side.
The scalar rule: exactly one value
A scalar subquery must return at most one row and exactly one column. If it returns two or more rows, most databases raise an error, such as PostgreSQL's "more than one row returned by a subquery used as an expression". This query fails for any customer with more than one order:
SELECT c.customer_id,
(SELECT o.total
FROM orders o
WHERE o.customer_id = c.customer_id) AS some_total
FROM customers c;Two details are worth knowing:
- The error happens at run time, when a customer with several orders is reached. It does not happen when the query is parsed. A query can pass testing on sparse data and fail in production.
- If the subquery returns zero rows, the value is NULL, with no error.
An aggregate guarantees one row, because an aggregate query with no GROUP BY always returns exactly one row. To fetch a non-aggregated value such as "the total of the latest order", you need a different approach. Options include a window function, or a limit clause such as ORDER BY order_date DESC FETCH FIRST 1 ROW ONLY (also written LIMIT 1 in some databases). Ties on the date can still make the result ambiguous.
Alternatives to the correlated subquery
The same questions can be written in other ways. Which one is clearest and fastest depends on the database and the data.
Join to a grouped derived table
SELECT o.order_id, o.customer_id, o.total
FROM orders o
JOIN (
SELECT customer_id, AVG(total) AS avg_total
FROM orders
GROUP BY customer_id
) a ON a.customer_id = o.customer_id
WHERE o.total > a.avg_total;The averages are computed once, in a single pass, and then joined back. This makes the work explicit, and it is useful when you need the average as an output column too. Because this is an inner join, customers without orders cannot appear. That is fine here, because the outer rows are the orders themselves.
Window function
SELECT order_id, customer_id, total
FROM (
SELECT order_id, customer_id, total,
AVG(total) OVER (PARTITION BY customer_id) AS avg_total
FROM orders
) t
WHERE total > avg_total;The window function adds the per-customer average to each row without collapsing rows. You must wrap it in a derived table, because WHERE is evaluated before window functions and cannot refer to them directly. Window functions are a good fit when the aggregate and the detail rows come from the same table, as they do here. They do not help when the aggregate comes from a different table than the outer row.
Choosing between them
| Form | Reads best when | Watch for |
|---|---|---|
| Correlated scalar subquery | The aggregate is a single value used once, and the outer table differs from the inner one | Run-time error if the subquery can return several rows. Possible per-row cost on engines that do not unnest it |
| Join to grouped derived table | You need the aggregate as a column, or you reuse it | Inner join drops outer rows with no group. Use LEFT JOIN to keep them |
| Window function | Detail rows and aggregate come from the same table | Needs a wrapping query to filter on the result |
Modern optimizers often rewrite a correlated scalar aggregate into a grouped join automatically, and the results are the same. If a query is slow, look at the execution plan before you rewrite it by hand. An index on the correlation column, here orders (customer_id), helps the correlated form, because each inner lookup then reads only that customer's orders.
Common mistakes
- Unqualified correlation column.
WHERE o2.customer_id = customer_idcompares the inner table with itself. Qualify every column. - Forgetting the empty case. A customer with no orders gets NULL from AVG, MAX, MIN, and SUM, and 0 from COUNT. Decide whether that is what you want.
- Expecting NULL totals to count as zero. Aggregates skip them.
- A subquery that can return several rows. Use an aggregate or a row limit, and handle ties.
- Using a subquery in SELECT and expecting it to filter. It only adds a column. To filter, put the condition in WHERE or use EXISTS.
Exercises
Exercise
Write a query that returns each order that is the largest order for its customer, using a correlated scalar subquery. Which orders does it return for the sample data?
Show answer
SELECT o.orderid, o.customerid, o.total FROM orders o WHERE o.total = ( SELECT MAX(o2.total) FROM orders o2 WHERE o2.customerid = o.customerid ); It returns order 102 (Ana, 150.00) and both orders 104 and 105 (Ben, 80.00 each), because ties for the maximum all match. Cy has no orders, so Cy contributes no rows.
Exercise
A colleague writes SELECT c.name, (SELECT o.orderdate FROM orders o WHERE o.customerid = c.customer_id) AS d FROM customers c; and it fails on the sample data. Why, and how do you fix it so it returns each customer's latest order date?
Show answer
Ana has three orders and Ben has two, so the subquery returns more than one row for those customers, which violates the scalar rule and raises an error. Replace o.orderdate with MAX(o.orderdate). The aggregate always returns one row, and Cy gets NULL because there are no orders.