Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Rewrite this nested query as a query with CTEs and explain what you gained: SELECT * FROM (SELECT customer_id, SUM(total) s FROM orders WHERE created_at >= '2025-01-01' GROUP BY customer_id) t JOIN customers c ON c.id = t.customer_id WHERE t.s > (SELECT AVG(s) FROM (SELECT SUM(total) s FROM orders WHERE created_at >= '2025-01-01' GROUP BY customer_id) x).

We name the per-customer spend aggregate once in a CTE and use that name twice: once to join to customers and once to compute the average. The query now reads top-down, and the two copies of the aggregate can no longer drift apart. On PostgreSQL 12 and later a CTE referenced twice is materialised by default, so the aggregate is also computed only once; MySQL 8.0 and later support CTEs too and may merge or materialise them.

Why this question is asked

Nested queries like this one appear in every reporting codebase. They work, but they hide the business rule, and they often repeat the same subquery with a tiny difference that nobody notices until the numbers are wrong. Interviewers ask for this rewrite because it shows whether we can make SQL readable and whether we know what the database actually does with a CTE. In this answer, we will recap what a CTE is, read the original query to see what it does, rewrite it, and then look at what we gained in readability, correctness and performance on PostgreSQL and MySQL.

1A Quick Recap of CTEs

A common table expression, or CTE, is a named subquery written at the top of a statement with the WITH keyword. After defining it, we can refer to it by name in the main query, as if it were a table that exists only for this one statement.

CTEs do not add new power for a simple query like ours; anything we write with a CTE we could write with derived tables, which are subqueries in the FROM clause. What they add is a name and an order. We read the statement from top to bottom: first the building blocks, then the query that combines them.

2Reading the Original Query

Before rewriting, we should be sure what the query does. Here it is, laid out with indentation.

SQL
SELECT *
FROM (SELECT customer_id, SUM(total) s
FROM orders
WHERE created_at >= '2025-01-01'
GROUP BY customer_id) t
JOIN customers c ON c.id = t.customer_id
WHERE t.s > (SELECT AVG(s)
FROM (SELECT SUM(total) s
FROM orders
WHERE created_at >= '2025-01-01'
GROUP BY customer_id) x);

The inner block t computes each customer's spend since 1 January 2025. The second block x computes the same spend again, without the customer_id column, only so that AVG(s) can find the average spend per customer. The outer query keeps customers whose spend is above that average.

Notice that the same aggregate is written twice. If someone later changes the date in t to '2025-04-01' and forgets x, the query still runs and returns plausible numbers, but it compares this quarter's spend against the average since January. That is the most dangerous kind of bug: no error, just a wrong report.

3The Rewrite With a CTE

We give the aggregate a name, spend, and use it twice.

SQL
WITH spend AS (
SELECT customer_id, SUM(total) AS s
FROM orders
WHERE created_at >= '2025-01-01'
GROUP BY customer_id
)
SELECT c.*, spend.s
FROM spend
JOIN customers c ON c.id = spend.customer_id
WHERE spend.s > (SELECT AVG(s) FROM spend);
-- Example data: customer 1 spent 300, customer 2 spent 100, customer 3 spent 50
-- AVG(s) = 150
-- Result: customer 1 with s = 300

The result is the same rows as before. We also replaced SELECT * with c.* and spend.s, because SELECT * over a join returns customer_id from spend and id from customers, two columns with the same value, and it changes shape whenever either table gains a column.

Now the statement reads like the business rule: 'compute spend per customer, then show the customers whose spend is above the average spend'. A reviewer can check the date once.

4What We Gained in Readability and Correctness

The first gain is that the aggregate is written once and named. There is one date filter, one definition of spend, so the two uses cannot drift apart. The name also documents the intent; spend says more than t or x.

The second gain is order. Nested derived tables are read from the inside out, which gets hard after two levels. With CTEs we can add more steps in sequence, for example a second CTE called above_average, and each step can be tested on its own by selecting from it directly while developing.

5What Happens to Performance

The performance story depends on the engine and version, so it is worth being precise. In PostgreSQL before version 12, every CTE was materialised: computed once, stored in a temporary result, and read from there. Since PostgreSQL 12, a CTE that is not recursive, has no side effects and is referenced only once is inlined, which means the planner treats it exactly like a subquery and can optimise through it.

Our CTE is referenced twice, so PostgreSQL 12 and later still materialise it by default. That is good here: the aggregate over orders is computed once and both the join and the AVG read the stored result. In the original query, the database had to scan and aggregate orders twice. We can see the difference in the plan.

Java
EXPLAIN SELECT ...; -- the WITH version
-- CTE spend
-- -> HashAggregate
-- -> Seq Scan on orders (Filter: created_at >= '2025-01-01')
-- InitPlan 2
-- -> Aggregate
-- -> CTE Scan on spend spend_1
-- -> Hash Join
-- -> CTE Scan on spend (Filter: s > (InitPlan 2).col1)
-- -> Hash
-- -> Seq Scan on customers
-- One scan of orders instead of two
How the engines treat the spend CTE
Engine and versionReferenced onceReferenced twice (our case)
PostgreSQL 11 and earlierMaterialisedMaterialised
PostgreSQL 12 and laterInlined like a subqueryMaterialised by default
PostgreSQL with AS MATERIALIZEDMaterialisedMaterialised
PostgreSQL with AS NOT MATERIALIZEDInlinedInlined, computed twice
MySQL 8.0 and laterUsually merged into the queryMaterialised once, or merged

We can also choose explicitly. WITH spend AS MATERIALIZED (...) forces the stored result, and WITH spend AS NOT MATERIALIZED (...) asks PostgreSQL to inline it even though it is referenced twice, which would mean computing it twice but lets outer filters push into it. The plan output above is simplified, and the exact node labels vary between versions.

6CTEs in MySQL

MySQL supports CTEs, including recursive ones, since version 8.0, so the same rewrite runs on MySQL 8.4. Its optimiser treats a CTE much like a derived table: it may merge it into the outer query, or materialise it into an internal temporary table, and when a CTE is referenced several times it can materialise it once and reuse it. EXPLAIN shows which one it chose; a materialised CTE appears as a derived table in the plan. The readability gain is the same on both engines; the performance gain depends on the plan, so we check EXPLAIN rather than assume.

7Follow-up questions

Is a CTE always faster than the nested version?

No. On PostgreSQL 12 and later a single-use CTE is planned exactly like the equivalent subquery, so it is neither faster nor slower. It helps when, as here, it lets the database compute something once instead of twice. It can hurt when materialisation stops a selective outer filter from reaching an index inside the CTE, which is why NOT MATERIALIZED exists.

Could we avoid the second reference with a window function?

Yes. We can compute AVG(s) OVER () in the CTE, which gives every row the overall average, and then filter in the outer query: WITH spend AS (SELECT customer_id, SUM(total) AS s, AVG(SUM(total)) OVER () AS avg_s FROM orders WHERE created_at >= '2025-01-01' GROUP BY customer_id) SELECT c.*, spend.s FROM spend JOIN customers c ON c.id = spend.customer_id WHERE spend.s > spend.avg_s. Window functions run after GROUP BY, so AVG over the grouped sums is allowed.

Why should the date be a parameter rather than a literal?

Because the report will be run for different periods, and a bind parameter lets the application pass the date safely and lets the database reuse the plan. With the CTE, there is only one place to put the parameter, which is another benefit of writing the aggregate once.

8Conclusion

In this answer, we rewrote a nested query with a CTE that names the per-customer spend once and uses it twice. The query reads top-down, and the two copies of the aggregate can no longer drift apart. On PostgreSQL 12 and later a CTE referenced twice is materialised by default, so orders is aggregated once instead of twice; AS MATERIALIZED and AS NOT MATERIALIZED let us override that choice, and MySQL 8.0 and later support the same syntax and may merge or materialise the CTE.

What to say in the interviewAbout 70 seconds aloud

Open with

I would pull the repeated aggregate into a CTE: WITH spend AS (SELECT customer_id, SUM(total) AS s FROM orders WHERE created_at >= '2025-01-01' GROUP BY customer_id), then SELECT c.*, spend.s FROM spend JOIN customers c ON c.id = spend.customer_id WHERE spend.s > (SELECT AVG(s) FROM spend).

Then, if they want more

The main gain is correctness and readability. The original wrote the same aggregate twice, so changing the date in one copy and not the other would silently produce a wrong report. Now there is one definition with a meaningful name, and the query reads in the order of the business rule.

On performance, since PostgreSQL 12 a CTE referenced once is inlined like a subquery, but one referenced twice, like this, is materialised by default, so orders is scanned and aggregated once instead of twice. If I wanted a different behaviour I can write AS MATERIALIZED or AS NOT MATERIALIZED.

MySQL supports CTEs since 8.0 and may merge or materialise them, so on either engine I would confirm the effect with EXPLAIN. I would also replace SELECT star with explicit columns.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 12, MySQL 8.0, MySQL 8.4
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.
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 "Rewrite this nested query as a query with CTEs and explain what you gained: SELECT *...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/8ed236240e/