← Learn SQL

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.

intermediate#sql#intermediate#cte#with#readability#refactoring

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:

See here how to connect with CloudBeaver, and how to run the koans

Right, and hard to read

Leo, thinking
Leo

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;
Mnemosyne, questioning
Mnemosyne

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?

Leo, thinking
Leo

Sure.

The nested version

Mnemosyne, talking
Mnemosyne

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

Mnemosyne, questioning
Mnemosyne

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;
the same average customer as in the subqueries lesson
Average customer
126193.54
Leo, excited
Leo

And it still gives 126193.54, the same average customer as in the subqueries lesson. But now I read it top to bottom.

Mnemosyne, questioning
Mnemosyne

That's a CTE — a common table expression. A subquery with a name, written before the query that uses it.

Leo, questioning
Leo

So customer_totals is a table now? Can I use it tomorrow?

Mnemosyne, questioning
Mnemosyne

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: 15
Leo, questioning
Leo

And the word WITH — is that standard SQL, or another PostgreSQL favour?

Mnemosyne, questioning
Mnemosyne

Standard SQL, since 1999. Every major database supports it today — MySQL only from version 8.

Use a step twice

Mnemosyne, pointing-right
Mnemosyne

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;
Leo, thinking
Leo

Once in FROM, once inside the average — and no second copy of the brackets.

30 rows — exactly the subqueries lesson's answer
CompanyName
Total sales
Fjord Foods
797164
Yarrow Pantry
786022.56
Quayside Traders
783579.03
…
…
Amber Grocers
186853.36
Emerald Grocers
175249.7
Mnemosyne, proud
Mnemosyne

Leo, the same 30 customers — Fjord Foods down to Emerald Grocers.

Leo, excited
Leo

Same answer — and this time the query was a bit easier to read.

One filter, and every use of the step sees it

Mnemosyne, talking
Mnemosyne

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;
Leo, proud
Leo

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;
Mnemosyne, smiling-eyes-open
Mnemosyne

One WITH, three steps, a comma between them — and each step can read the steps above it.

row for row, last lesson's answer
CompanyName
Total sales
Freight
Baltic Supermarket
9445.2
752.27
Golden Pantry
18342.33
744.17
Nordic Foods
11322.73
709.59
Alpine Provisions
15686.56
610.83
Quayside Wholefoods
3102.87
571.5
Mnemosyne, proud
Mnemosyne

Baltic Supermarket first on 752.27 — last lesson's answer, row for row.

Leo, smiling-eyes-open
Leo

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;
Mnemosyne, questioning
Mnemosyne

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.

every customer, counted and added up
Customers
Sales
Freight
47
262931.17
11819.17
Leo, proud
Leo

Nothing changed further down: 47 customers, 262931.17 in sales, 11819.17 in freight — the same as last lesson's version, without its LIMIT.

Mnemosyne, questioning
Mnemosyne

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"
)
Leo, proud
Leo

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.

Mnemosyne, questioning
Mnemosyne

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;
the merged version's top five, by freight
CompanyName
Total sales
Freight
Quayside Wholefoods
3102.87
3409.7
Nordic Foods
11322.73
3295.76
Golden Pantry
18342.33
2414.54
Emerald Grocers
2744.71
1951.72
Alpine Provisions
15686.56
1814.54
Leo, surprised
Leo

Quayside is top on freight now — and it was fifth.

Mnemosyne, questioning
Mnemosyne

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;
the same check, on both versions
Version
Customers
Sales
Freight
two steps
47
262931.17
11819.17
merged into one
47
262931.17
37749.51
Leo, thinking
Leo

Same 47 customers, the same sales to the cent — and more than three times the freight.

Mnemosyne, pointing-right
Mnemosyne

Only the freight moved. That's why it's in the check.

Leo, thinking
Leo

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

Mnemosyne, questioning
Mnemosyne

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";
Leo, thinking
Leo

Inside one step. I point the final SELECT at month_orders, for Quayside Wholefoods, and read what it held before anything summed it.

OrderID
CustomerID
Freight
8415
QUAY3
3.86
8472
QUAY3
567.64
Mnemosyne, proud
Mnemosyne

Two orders in May: 3.86 and 567.64. Together, 571.5.

Leo, thinking
Leo

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

Leo, questioning
Leo

Mnemosyne, the CTE made that mistake easy to find. Does it make the query faster too?

Mnemosyne, smiling-eyes-open
Mnemosyne

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.

Leo, questioning
Leo

And the person reading it next month is usually me.

What to take away, and what is next

Mnemosyne, questioning
Mnemosyne

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.

Leo, smiling-eyes-open
Leo

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

Mnemosyne, excited
Mnemosyne

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.

Leo, excited
Leo

So customer_totals could be a view in the database — and every query would just reuse it.

That's all, folks!

  1. Subqueries — one query's result inside another
  2. CASE — SQL's if/then for labels & buckets
  3. Dates & Times — ranges and boundaries
  4. Multi-Table JOINs & Grain — rows dropped or multiplied
  5. CTEs (WITH) — a long query, in named steps (this lesson)
  6. VIEWs, CREATE TABLE AS & Temp Tables — query or answer
  7. EXISTS & Correlated Subqueries — and the NOT IN trap
  8. Self-JOINs & Hierarchies — rows in the same table
  9. Window Functions I: OVER, PARTITION BY & ROW_NUMBER
  10. String Functions, LIKE & Regex — clean up messy data
  11. Window Functions II: LAG/LEAD, Running Totals & Frames
  12. UNION, INTERSECT, EXCEPT — stack and reconcile lists
  13. GROUPING SETS, ROLLUP & CUBE — subtotals in one pass
  14. INSERT, UPDATE, DELETE & Transactions — safely
  15. UPSERT & MERGE — insert or update, safely re-run
  16. Median and Percentiles — WITHIN GROUP, not AVG
  17. 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