Quick revision
The short answer
The correlated version compares each order with a subquery that averages that customer's orders: WHERE o.total > (SELECT AVG(o2.total) FROM orders o2 WHERE o2.customer_id = o.customer_id). The window version computes AVG(total) OVER (PARTITION BY customer_id) for every row in one pass, in a derived table, and filters on it outside. The correlated form may run its subquery once per order unless the planner decorrelates it, so an index on (customer_id, total) helps it a lot, while the window form scans orders once and sorts or hashes by customer.
What to remember
In this answer, we wrote the correlated subquery that compares each order with the average of that customer's orders, and rewrote it with AVG(total) OVER (PARTITION BY customer_id) in a derived table, filtered outside because window functions run after WHERE. We saw that the correlated form may run per row unless decorrelated, so an index on (customer_id, total) is what keeps it fast, while the window form scans once and pays for a sort or hash by customer.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The correlated version compares each order with a subquery that averages that customer's orders: WHERE o.total > (SELECT AVG(o2.total) FROM orders o2 WHERE o2.customer_id = o.customer_id). The window version computes AVG(total) OVER (PARTITION BY customer_id) for every row in one pass, in a derived table, and filters on it outside. The correlated form may run its subquery once per order unless the planner decorrelates it, so an index on (customer_id, total) helps it a lot, while the window form scans orders once and sorts or hashes by customer.
Why this question is asked
Comparing a row with an aggregate of its own group is one of the most common reporting needs: orders above the customer's average, employees paid more than their department's median, days above the monthly mean. There are two natural ways to write it, and they perform very differently as data grows. Interviewers ask for both to check that we can write a correlated subquery, that we know window functions, and that we understand what each costs. In this answer, we will set up small data, write the correlated query, rewrite it with a window function, and compare how each one runs.
1A Quick Recap of Correlated Subqueries and Window Functions
A correlated subquery is a subquery that refers to a column of the outer query, so its result depends on the current outer row. Logically, it is evaluated again for every outer row. A window function computes a value over a set of rows related to the current row, called the window, without collapsing those rows into one the way GROUP BY does. AVG(total) OVER (PARTITION BY customer_id) gives every row the average of all rows with the same customer_id, while keeping every row in the result.
2Writing the Correlated Subquery
Here is a small data set. Ada's orders average 20, Ben's average 50.
The subquery uses o.customer_id from the outer row, which is what makes it correlated. For order 3, it computes the average of customer 1's orders, 20, and 30 > 20 keeps the row. For order 4, the average is 50, and 50 > 50 is false. Notice that we need two aliases for the same table, o and o2, so the subquery's customer_id can be compared with the outer one.
3Rewriting It With a Window Function
The window version computes each customer's average next to every order, in one pass. We cannot use a window function directly in WHERE, because window functions are evaluated after WHERE, so we compute it in a derived table and filter outside.
Same result, but the work is organised differently. The inner query reads all orders once, groups them by customer through a sort or a hash, computes each partition's average and attaches it to every row. The outer query is then a simple filter. A bonus is that avg_total is available in the result, so we can show it on the report without a second query.
4How Each Version Runs
Logically, the correlated subquery runs once per outer row. If orders has 10 million rows and no helpful index, that would be 10 million aggregations, each scanning the customer's orders. Some planners can decorrelate it, rewriting it into a join against a grouped derived table, which is essentially the same as computing all averages first; MySQL 8.0 has an optional transformation for correlated scalar subqueries (check your version), while PostgreSQL runs this shape as a SubPlan executed per outer row. So in PostgreSQL the index matters a lot: with an index on (customer_id, total), each subquery execution is an index-only scan over just that customer's entries, perhaps a few dozen rows, instead of a scan of the table.
The window version scans orders once. Its main cost is grouping rows by customer: a sort of 10 million rows, which may spill to disk if it exceeds work_mem, or a cheaper ordered read if an index on customer_id provides the order. Its cost grows roughly with the table size and does not multiply.
| Correlated subquery | Window function | |
|---|---|---|
| Passes over orders | One, plus one subquery per row | One |
| Main cost | Per-row aggregate (needs an index) | Sort or hash by customer |
| Best index | (customer_id, total) | customer_id, to avoid the sort |
| Good when | Few outer rows, such as one page | Whole table or large reports |
| Average in the output | Needs another subquery | Yes, as a column |
5Which One to Choose
For a report over the whole table, the window function is usually the better choice: one scan, predictable cost, and the average comes for free. The correlated subquery shines when the outer query is small, for example checking 50 orders on one page, because then it does 50 cheap index probes and never touches the rest of the table, while the window version would still compute averages over every partition it reads.
The equivalent join form is a third option: join orders to a derived table of (customer_id, AVG(total)) grouped by customer. It is what decorrelation produces and works in every database. Whichever we pick, we confirm with EXPLAIN ANALYZE on realistic data, and we keep in mind that the window version includes NULL totals in the partition but AVG ignores them, the same as the subquery, so both treat NULLs alike.
6Follow-up questions
Why can't a window function be used directly in WHERE?
Because of the logical order of evaluation. FROM and WHERE run first and decide which rows exist, then GROUP BY and HAVING, then window functions are computed over the remaining rows, and only then SELECT and ORDER BY. A filter on a window result would have to run before the window exists. So we compute it in a derived table or CTE and filter in the outer query. Some databases add a QUALIFY clause for this; PostgreSQL and MySQL do not have it.
Is the window version always faster?
No. For a whole-table report it usually is, but if the outer query is restricted to a few customers or a page of orders, the correlated subquery with a good index does very little work, and the window version may read more rows than needed. The honest answer is to compare plans and timings for the real query shape.
How would you get each customer's top order instead of the average?
With ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY total DESC) in a derived table, keeping rn = 1. Or, in PostgreSQL, DISTINCT ON (customer_id) ordered by customer_id and total DESC, or a LATERAL subquery with LIMIT 1 per customer, which is the fastest when there is an index and the groups are large.
7Conclusion
In this answer, we wrote the correlated subquery that compares each order with the average of that customer's orders, and rewrote it with AVG(total) OVER (PARTITION BY customer_id) in a derived table, filtered outside because window functions run after WHERE. We saw that the correlated form may run per row unless decorrelated, so an index on (customer_id, total) is what keeps it fast, while the window form scans once and pays for a sort or hash by customer.
Open with
The correlated version is SELECT o.* FROM orders o WHERE o.total > (SELECT AVG(o2.total) FROM orders o2 WHERE o2.customer_id = o.customer_id). It is correlated because the subquery uses the outer row's customer_id, so logically it runs once per order.
Then, if they want more
The window version computes AVG(total) OVER (PARTITION BY customer_id) as a column in a derived table, and filters total > avg_total in the outer query, because window functions are evaluated after WHERE and cannot be used there directly. Both return the same rows. The performance difference is in how they run.
In PostgreSQL the correlated form is a SubPlan executed per outer row, so without an index it would scan orders for every order. With an index on customer_id and total, each execution is a short index-only scan over that customer's orders, which is fine for a page of results.
Some engines can decorrelate it into a join against grouped averages, MySQL has an optional transformation for that, but I would not rely on it.
The window version reads orders once and sorts or hashes it by customer, so its cost grows with the table, not with table times customers, and it gives me the average as a column for the report.
So for whole-table reporting I would use the window function, for a small filtered set the correlated subquery with the index is fine, and I would check both with EXPLAIN ANALYZE.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 8.0
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a correlated subquery that returns each order whose total is above the average...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/90b421c3fa/