CTEs (WITH) — Breaking a Long Query Into Named Steps
Give each step of a long query a name with WITH, use a step more than once, write a filter once for every use of a step, read and debug the steps one at a time, and check that a rewrite returns exactly what the original did.
This article is part of the Learn SQL hands-on course series.
Prerequisite — this is a hands-on lesson. Reading it is not enough. Run every query yourself in CloudBeaver, against the Northwind Company sample database on PostgreSQL — and solve the koans yourself on DuckDB, the same Northwind Company data.
Not set up yet? It only takes a couple of minutes:
Right, and hard to read
Mnemosyne, last lesson's freight SQL query gives the right answer, but I can't read it. The dates for the month of May are in it twice — to change the month, I have to find both.
SELECT c."CompanyName", s."Total sales", f."Freight"
FROM "Customers" c
JOIN (SELECT o."CustomerID",
ROUND(SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")), 2) AS "Total sales"
FROM "Orders" o
JOIN "Order Details" d
ON d."OrderID" = o."OrderID"
WHERE o."OrderDate" >= DATE '2024-05-01'
AND o."OrderDate" < DATE '2024-06-01'
GROUP BY o."CustomerID") AS s
ON s."CustomerID" = c."CustomerID"
JOIN (SELECT "CustomerID",
SUM("Freight") AS "Freight"
FROM "Orders"
WHERE "OrderDate" >= DATE '2024-05-01'
AND "OrderDate" < DATE '2024-06-01'
GROUP BY "CustomerID") AS f
ON f."CustomerID" = c."CustomerID"
ORDER BY f."Freight" DESC
LIMIT 5;Then let's give each step a name. As you may remember, you said the same about a query in our lesson on subqueries. Can we start with that one, then come back to this one?
Sure.
The nested version
Here it is: the customers above the average customer. Read it from the inside out: the innermost brackets build one total per customer, the brackets around them average those totals, and the query outside compares each customer with the average. The same customer total is written three times — the blue lines.
SELECT c."CompanyName",
ROUND(SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")), 2) AS "Total sales"
FROM "Customers" c
JOIN "Orders" o
ON o."CustomerID" = c."CustomerID"
JOIN "Order Details" d
ON d."OrderID" = o."OrderID"
GROUP BY c."CompanyName"
HAVING SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount"))
> (SELECT AVG(t."Total")
FROM (SELECT o2."CustomerID",
SUM(d2."UnitPrice"
* d2."Quantity"
* (1 - d2."Discount")) AS "Total"
FROM "Orders" o2
JOIN "Order Details" d2
ON d2."OrderID" = o2."OrderID"
GROUP BY o2."CustomerID") AS t)
ORDER BY "Total sales" DESC;WITH: give the brackets a name
Take those innermost brackets out and give them a name, customer_totals, written first, after WITH. The query underneath reads the name like a table.
WITH customer_totals AS (
SELECT o."CustomerID",
SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")) AS "Total"
FROM "Orders" o
JOIN "Order Details" d
ON d."OrderID" = o."OrderID"
GROUP BY o."CustomerID"
)
SELECT ROUND(AVG("Total"), 2) AS "Average customer"
FROM customer_totals;And it still gives 126193.54, the same average customer as in the subqueries lesson. But now I read it top to bottom.
That's a CTE — a common table expression. A subquery with a name, written before the query that uses it.
So customer_totals is a table now? Can I use it tomorrow?
Only inside this one query. Nothing is stored — the name lasts until the semicolon. But inside the query, you can use it as often as you like.
SELECT * FROM customer_totals;SQL Error [42P01]: ERROR: relation "customer_totals" does not exist
Position: 15And the word WITH — is that standard SQL, or another PostgreSQL favour?
Standard SQL, since 1999. Every major database supports it today — MySQL only from version 8.
Use a step twice
Now let's rewrite the whole query, the customers above the average customer, with the CTE. customer_totals feeds the list of customers and the average they are compared with.
WITH customer_totals AS (
SELECT o."CustomerID",
SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")) AS "Total"
FROM "Orders" o
JOIN "Order Details" d
ON d."OrderID" = o."OrderID"
GROUP BY o."CustomerID"
)
SELECT c."CompanyName",
ROUND(t."Total", 2) AS "Total sales"
FROM customer_totals t
JOIN "Customers" c
ON c."CustomerID" = t."CustomerID"
WHERE t."Total" > (SELECT AVG("Total")
FROM customer_totals)
ORDER BY "Total sales" DESC;Once in FROM, once inside the average — and no second copy of the brackets.
Leo, the same 30 customers — Fjord Foods down to Emerald Grocers.
Same answer — and this time the query was a bit easier to read.
One filter, and every use of the step sees it
Now, let's come back to your freight SQL query. The dates for May are written twice, once for the sales and once for the freight. Move one bracket to June, forget the other, and it still runs: 39 customers, June's sales beside the freight from May.
SELECT c."CompanyName", s."Total sales", f."Freight"
FROM "Customers" c
JOIN (SELECT o."CustomerID",
ROUND(SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")), 2) AS "Total sales"
FROM "Orders" o
JOIN "Order Details" d
ON d."OrderID" = o."OrderID"
WHERE o."OrderDate" >= DATE '2024-05-01'
AND o."OrderDate" < DATE '2024-06-01'
GROUP BY o."CustomerID") AS s
ON s."CustomerID" = c."CustomerID"
JOIN (SELECT "CustomerID",
SUM("Freight") AS "Freight"
FROM "Orders"
WHERE "OrderDate" >= DATE '2024-05-01'
AND "OrderDate" < DATE '2024-06-01'
GROUP BY "CustomerID") AS f
ON f."CustomerID" = c."CustomerID"
ORDER BY f."Freight" DESC
LIMIT 5;Then I'll write the dates for the month of May once. month_orders holds the orders from May, and both sales and freight read it — change the month there, and both see it.
WITH month_orders AS (
SELECT "OrderID", "CustomerID", "Freight"
FROM "Orders"
WHERE "OrderDate" >= DATE '2024-05-01'
AND "OrderDate" < DATE '2024-06-01'
),
sales AS (
SELECT o."CustomerID",
ROUND(SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")), 2) AS "Total sales"
FROM month_orders o
JOIN "Order Details" d ON d."OrderID" = o."OrderID"
GROUP BY o."CustomerID"
),
freight AS (
SELECT "CustomerID",
SUM("Freight") AS "Freight"
FROM month_orders
GROUP BY "CustomerID"
)
SELECT c."CompanyName", s."Total sales", f."Freight"
FROM "Customers" c
JOIN sales s ON s."CustomerID" = c."CustomerID"
JOIN freight f ON f."CustomerID" = c."CustomerID"
ORDER BY f."Freight" DESC
LIMIT 5;One WITH, three steps, a comma between them — and each step can read the steps above it.
Baltic Supermarket first on 752.27 — last lesson's answer, row for row.
And next month I change one step, not two brackets.
Check every customer, not just the top five
The query on the left: Leo's query: shows only the top five
WITH month_orders AS ( … ),
sales AS ( … ), freight AS ( … )
SELECT c."CompanyName", s."Total sales", f."Freight"
FROM "Customers" c
JOIN sales s ON s."CustomerID" = c."CustomerID"
JOIN freight f ON f."CustomerID" = c."CustomerID"
ORDER BY f."Freight" DESC
LIMIT 5;The query on the right: the check: the same query as a step, no LIMIT, counted and added up
WITH month_orders AS ( … ),
sales AS ( … ), freight AS ( … ),
sales_and_freight AS (
SELECT c."CompanyName", s."Total sales", f."Freight"
FROM "Customers" c
JOIN sales s ON s."CustomerID" = c."CustomerID"
JOIN freight f ON f."CustomerID" = c."CustomerID"
)
SELECT COUNT(*) AS "Customers",
SUM("Total sales") AS "Sales",
SUM("Freight") AS "Freight"
FROM sales_and_freight;Same top five — but the LIMIT shows only five customers, and a rewrite can change one further down. So check them all: here your query, without the LIMIT, becomes one more step, sales_and_freight, and the query below counts its rows and adds up its totals.
Nothing changed further down: 47 customers, 262931.17 in sales, 11819.17 in freight — the same as last lesson's version, without its LIMIT.
Do that after every rewrite: count the rows, add up the totals, and compare them with the original. And keep the freight in it — after a join to the order lines, it would be added up once per line instead of once per order.
The check, written out in full, to run in CloudBeaver:
WITH month_orders AS (
SELECT "OrderID", "CustomerID", "Freight"
FROM "Orders"
WHERE "OrderDate" >= DATE '2024-05-01'
AND "OrderDate" < DATE '2024-06-01'
),
sales AS (
SELECT o."CustomerID",
ROUND(SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")), 2) AS "Total sales"
FROM month_orders o
JOIN "Order Details" d ON d."OrderID" = o."OrderID"
GROUP BY o."CustomerID"
),
freight AS (
SELECT "CustomerID",
SUM("Freight") AS "Freight"
FROM month_orders
GROUP BY "CustomerID"
),
sales_and_freight AS (
SELECT c."CompanyName", s."Total sales", f."Freight"
FROM "Customers" c
JOIN sales s ON s."CustomerID" = c."CustomerID"
JOIN freight f ON f."CustomerID" = c."CustomerID"
)
SELECT COUNT(*) AS "Customers",
SUM("Total sales") AS "Sales",
SUM("Freight") AS "Freight"
FROM sales_and_freight;The merge that looks like a tidy-up
The query on the left: two steps
sales AS (
SELECT o."CustomerID",
ROUND(SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")), 2) AS "Total sales"
FROM month_orders o
JOIN "Order Details" d ON d."OrderID" = o."OrderID"
GROUP BY o."CustomerID"
),
freight AS (
SELECT "CustomerID",
SUM("Freight") AS "Freight"
FROM month_orders
GROUP BY "CustomerID"
)The query on the right: merged into one
totals AS (
SELECT o."CustomerID",
ROUND(SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")), 2) AS "Total sales",
SUM(o."Freight") AS "Freight"
FROM month_orders o
JOIN "Order Details" d ON d."OrderID" = o."OrderID"
GROUP BY o."CustomerID"
)sales and freight both read month_orders, and both give one row per customer. Why two steps? I'll write one, totals, with both sums in it.
Run it.
The merged version, written out in full:
WITH month_orders AS (
SELECT "OrderID", "CustomerID", "Freight"
FROM "Orders"
WHERE "OrderDate" >= DATE '2024-05-01'
AND "OrderDate" < DATE '2024-06-01'
),
totals AS (
SELECT o."CustomerID",
ROUND(SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")), 2) AS "Total sales",
SUM(o."Freight") AS "Freight"
FROM month_orders o
JOIN "Order Details" d ON d."OrderID" = o."OrderID"
GROUP BY o."CustomerID"
)
SELECT c."CompanyName", t."Total sales", t."Freight"
FROM "Customers" c
JOIN totals t ON t."CustomerID" = c."CustomerID"
ORDER BY t."Freight" DESC
LIMIT 5;Quayside is top on freight now — and it was fifth.
Leo, keep Quayside in mind. Now run the same check on both versions, side by side.
Two steps against one: only the freight moved
The same check on the merged version, with totals in place of sales and freight:
WITH month_orders AS (
SELECT "OrderID", "CustomerID", "Freight"
FROM "Orders"
WHERE "OrderDate" >= DATE '2024-05-01'
AND "OrderDate" < DATE '2024-06-01'
),
totals AS (
SELECT o."CustomerID",
ROUND(SUM(d."UnitPrice" * d."Quantity"
* (1 - d."Discount")), 2) AS "Total sales",
SUM(o."Freight") AS "Freight"
FROM month_orders o
JOIN "Order Details" d ON d."OrderID" = o."OrderID"
GROUP BY o."CustomerID"
),
sales_and_freight AS (
SELECT c."CompanyName", t."Total sales", t."Freight"
FROM "Customers" c
JOIN totals t ON t."CustomerID" = c."CustomerID"
)
SELECT COUNT(*) AS "Customers",
SUM("Total sales") AS "Sales",
SUM("Freight") AS "Freight"
FROM sales_and_freight;Same 47 customers, the same sales to the cent — and more than three times the freight.
Only the freight moved. That's why it's in the check.
If I'd checked rows and sales and stopped there, I'd have sent that out. It ran without errors, and it almost fooled me into thinking it was correct.
Look inside one step
You didn't stop there, Leo. When a number looks wrong, where do you look first?
WITH month_orders AS (
SELECT "OrderID", "CustomerID", "Freight"
FROM "Orders"
WHERE "OrderDate" >= DATE '2024-05-01'
AND "OrderDate" < DATE '2024-06-01'
)
SELECT *
FROM month_orders
WHERE "CustomerID" = 'QUAY3'
ORDER BY "OrderID";Inside one step. I point the final SELECT at month_orders, for Quayside Wholefoods, and read what it held before anything summed it.
Two orders in May: 3.86 and 567.64. Together, 571.5.
So the step is right, and my merged step was wrong: it added each order's freight once per order line, and one of those orders has six lines. That's the same mistake as last lesson, only now inside a step. Calling it totals didn't make it right.
Your turn, Leo.
Run the report for June 2024: change the month in its one step.
Who pays the most freight in June? Juniper Trading, on 1126.69.
▶ Continue once you've run it.
WITH month_orders AS (
SELECT "OrderID", "CustomerID", "Freight" FROM "Orders"
WHERE "OrderDate" >= DATE '2024-06-01'
AND "OrderDate" < DATE '2024-07-01'
), sales AS ( … ), freight AS ( … )For reading, not for speed
Mnemosyne, the CTE made that mistake easy to find. Does it make the query faster too?
Don't count on it. The database is free to treat a CTE just like the subquery it replaced. A CTE is for the person reading the query — speed has its own lessons in Series 3.
And the person reading it next month is usually me.
What to take away, and what is next
Leo, then write it so you can read it next month. Here are four rules. Name a step, then use the name. A step can read the ones above it, and be used twice. Write the dates for the month of May once, in the step that picks the orders. And add up the freight in a step without the order lines — after a join to them, it would be added up once per line instead of once per order.
The first two make it readable. The last two keep the answer right when I shorten it.
Your turn, Leo.
▶ Walk the path to enlightenment.
cd c:/DataPallas/db/datazeus
.\zeus.bat koans learnsql series2 _20- name it, then use the name: the three biggest categories
- use a step twice: categories above the average category
- one step reads another: sales per order, per sales rep
- …and seven more, ending with two you write yourself
…/learnsql/series2/_20/CtesKoans.groovy
Leo, that was WITH. Name each step, read them top to bottom, and check every total after a rewrite. Next lesson: views — a step with a name that outlives the query.
So customer_totals could be a view in the database — and every query would just reuse it.
That's all, folks!
- Subqueries — one query's result inside another
- CASE — SQL's if/then for labels & buckets
- Dates & Times — ranges and boundaries
- Multi-Table JOINs & Grain — rows dropped or multiplied
- CTEs (WITH) — a long query, in named steps (this lesson)
- VIEWs, CREATE TABLE AS & Temp Tables — query or answer
- EXISTS & Correlated Subqueries — and the NOT IN trap
- Self-JOINs & Hierarchies — rows in the same table
- Window Functions I: OVER, PARTITION BY & ROW_NUMBER
- String Functions, LIKE & Regex — clean up messy data
- Window Functions II: LAG/LEAD, Running Totals & Frames
- UNION, INTERSECT, EXCEPT — stack and reconcile lists
- GROUPING SETS, ROLLUP & CUBE — subtotals in one pass
- INSERT, UPDATE, DELETE & Transactions — safely
- UPSERT & MERGE — insert or update, safely re-run
- Median and Percentiles — WITHIN GROUP, not AVG
- Subqueries + CTEs + Window Functions — a real case
Found this to be a little gem? Help others find it too — someone out there is stuck trying to learn SQL right now. The button opens Reddit with the link and title already filled in, so you just pick a community and post.
Share on Reddit