Skip to main content

Databases · Intermediate · 20 min

Break a long SQL query into readable steps with CTEs

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7

You will rewrite a 47-line nested PostgreSQL 18 report as a chain of named WITH steps you can check one at a time, read in EXPLAIN when PostgreSQL inlines a CTE and when it does not, and move old rows to an archive in one statement.

On this page

A report query tends to grow one subquery at a time. Each change is small, but after a few months you have 47 lines where the same filter appears three times, the same subquery twice, and nobody can say which part produces which number. When a figure looks wrong, you cannot test half of it.

A common table expression (CTE) fixes that. WITH name AS (...) gives a piece of a query a name, and later pieces read from that name as if it were a table. The query becomes a list of steps, top to bottom, and you can run any step on its own to check it.

In this tutorial you load a small delivery shop's orders into PostgreSQL 18, run an October sales report written the nested way, and rewrite it as a chain of named steps that returns exactly the same rows. Then you compare a CTE with a subquery and a view, use EXPLAIN to see when PostgreSQL folds a CTE into the main query and when MATERIALIZED changes the plan, and finish with a single statement that moves cancelled orders and their items to archive tables. Recursive CTEs, which walk trees, are covered in /tutorials/model-many-to-many-relationships-and-trees-in-sql.

You need PostgreSQL 18 on Ubuntu 26.04, installed as in /tutorials/install-postgresql-18-on-ubuntu-26-04. PostgreSQL 19.0 came out on 19 November 2026; everything here works the same on it. Each piece of SQL is saved to a file under ~/cte-demo and run with psql, so you can edit and rerun it. If you prefer, paste the same SQL into an interactive session opened with sudo -u postgres psql -d shop.

Step 1 · Load a small shop's orders

Make a working folder and an empty database called shop:

Bash
mkdir -p ~/cte-demo
sudo -u postgres createdb shop

Now write the data file. It creates three tables: customers in four cities, orders placed between 1 September and 31 October 2026, and order_items, one to three lines per order. The rows are built from generate_series with fixed arithmetic rather than random numbers, so your totals will match the ones shown below exactly.

Bash
cat > ~/cte-demo/shop.sql <<'SQL'
\set ON_ERROR_STOP on
DROP TABLE IF EXISTS order_items, orders, customers;

CREATE TABLE customers (
  id   integer PRIMARY KEY,
  name text NOT NULL,
  city text NOT NULL
);
INSERT INTO customers (id, name, city)
SELECT g, 'Customer ' || g,
       (ARRAY['Lagos', 'Nairobi', 'Accra', 'Kigali'])[1 + g % 4]
FROM generate_series(1, 500) AS g;

CREATE TABLE orders (
  id          integer PRIMARY KEY,
  customer_id integer NOT NULL REFERENCES customers (id),
  ordered_on  date    NOT NULL,
  status      text    NOT NULL
);
INSERT INTO orders (id, customer_id, ordered_on, status)
SELECT g,
       1 + (g * 13 + g / 7) % 500,
       date '2026-09-01' + g % 61,
       CASE WHEN g % 10 = 0 THEN 'cancelled' ELSE 'paid' END
FROM generate_series(1, 2000) AS g;

CREATE TABLE order_items (
  order_id   integer       NOT NULL REFERENCES orders (id) ON DELETE CASCADE,
  line       integer       NOT NULL,
  product    text          NOT NULL,
  qty        integer       NOT NULL,
  unit_price numeric(10,2) NOT NULL,
  PRIMARY KEY (order_id, line)
);
INSERT INTO order_items (order_id, line, product, qty, unit_price)
SELECT o.id, line,
       (ARRAY['Rice 5 kg', 'Palm oil 1 L', 'Exercise book', 'Bar soap'])[1 + (o.id + line) % 4],
       1 + (o.id * line) % 4,
       (ARRAY[8500, 3200, 600, 450])[1 + (o.id + line) % 4]
FROM orders o
CROSS JOIN LATERAL generate_series(1, 1 + o.id % 3) AS line;

CREATE INDEX orders_customer_id_idx ON orders (customer_id);
ANALYZE;
SQL
sudo -u postgres psql -d shop < ~/cte-demo/shop.sql

The shell reads the file and hands it to psql on standard input, so the postgres user never needs access to your home folder. \set ON_ERROR_STOP on makes psql stop at the first error instead of carrying on through the rest of the file. The ON DELETE CASCADE on order_items means deleting an order deletes its lines too; the last step relies on that. Prices are whole units of a local currency.

Check it worked

Bash
sudo -u postgres psql -d shop -c "SELECT (SELECT count(*) FROM customers) AS customers, (SELECT count(*) FROM orders) AS orders, (SELECT count(*) FROM order_items) AS items;"

You see 500, 2000 and 4001. If createdb says the database already exists, you ran this step before; the DROP TABLE IF EXISTS line at the top of the file makes it safe to load again.

Step 2 · Run the report written the nested way

The question: for paid orders in October 2026, how many customers ordered in each city, how many orders were there, how much revenue, what was the average order value, and what share of revenue came from repeat customers (those with two or more paid orders in October)?

Here is the answer as it often ends up in a codebase, built inside out. Save it:

Bash
cat > ~/cte-demo/report_nested.sql <<'SQL'
\set ON_ERROR_STOP on
SELECT city_stats.city,
       city_stats.customers,
       city_stats.orders,
       city_stats.revenue,
       round(city_stats.revenue / city_stats.orders, 2) AS avg_order,
       round(100.0 * coalesce(repeaters.revenue, 0) / city_stats.revenue, 1) AS repeat_pct
FROM (
  SELECT c.city,
         count(DISTINCT t.customer_id) AS customers,
         count(*) AS orders,
         sum(t.total) AS revenue
  FROM (
    SELECT o.id, o.customer_id, sum(i.qty * i.unit_price) AS total
    FROM orders o
    JOIN order_items i ON i.order_id = o.id
    WHERE o.status = 'paid'
      AND o.ordered_on >= date '2026-10-01'
      AND o.ordered_on <  date '2026-11-01'
    GROUP BY o.id, o.customer_id
  ) AS t
  JOIN customers c ON c.id = t.customer_id
  GROUP BY c.city
) AS city_stats
LEFT JOIN (
  SELECT c.city, sum(t.total) AS revenue
  FROM (
    SELECT o.id, o.customer_id, sum(i.qty * i.unit_price) AS total
    FROM orders o
    JOIN order_items i ON i.order_id = o.id
    WHERE o.status = 'paid'
      AND o.ordered_on >= date '2026-10-01'
      AND o.ordered_on <  date '2026-11-01'
    GROUP BY o.id, o.customer_id
  ) AS t
  JOIN customers c ON c.id = t.customer_id
  WHERE t.customer_id IN (
    SELECT o.customer_id
    FROM orders o
    WHERE o.status = 'paid'
      AND o.ordered_on >= date '2026-10-01'
      AND o.ordered_on <  date '2026-11-01'
    GROUP BY o.customer_id
    HAVING count(*) >= 2
  )
  GROUP BY c.city
) AS repeaters ON repeaters.city = city_stats.city
ORDER BY city_stats.revenue DESC, city_stats.city;
SQL
sudo -u postgres psql -d shop < ~/cte-demo/report_nested.sql
Text
  city   | customers | orders |  revenue   | avg_order | repeat_pct
---------+-----------+--------+------------+-----------+------------
 Nairobi |       123 |    260 | 4699550.00 |  18075.19 |       89.2
 Kigali  |       123 |    259 | 4667000.00 |  18019.31 |       87.1
 Accra   |       123 |    259 | 4644050.00 |  17930.69 |       88.7
 Lagos   |       103 |    131 | 2382750.00 |  18188.93 |       41.3
(4 rows)

The answer is right, but look at what it costs to maintain. The October filter is written three times. The per-order totals subquery is written twice, word for word. To read it you start in the middle, at the innermost SELECT, and work outwards. If someone changes "October" in two places and misses the third, the repeat share quietly goes wrong.

Check it worked

You get four rows, one per city, with Nairobi first and Lagos last. Lagos has the smallest share of revenue from repeat customers, about 41 percent. If you see ERROR and nothing else, compare your file with the one above; ON_ERROR_STOP stopped psql at the first mistake.

Step 3 · Rewrite it as a chain of named steps

Each subquery above answers one small question. Give each one a name in a WITH list, in the order you would explain the report to a colleague:

  1. october_orders: which paid orders fall in October.
  2. order_totals: what each of those orders was worth.
  3. repeat_customers: who ordered at least twice in October.
  4. city_stats: the totals per city, with repeat revenue counted separately.

The final SELECT reads only from the last step and does the presentation: rounding, percentages and sort order.

Bash
cat > ~/cte-demo/report_cte.sql <<'SQL'
\set ON_ERROR_STOP on
WITH october_orders AS (
  SELECT id, customer_id
  FROM orders
  WHERE status = 'paid'
    AND ordered_on >= date '2026-10-01'
    AND ordered_on <  date '2026-11-01'
),
order_totals AS (
  SELECT o.id, o.customer_id, sum(i.qty * i.unit_price) AS total
  FROM october_orders o
  JOIN order_items i ON i.order_id = o.id
  GROUP BY o.id, o.customer_id
),
repeat_customers AS (
  SELECT customer_id
  FROM october_orders
  GROUP BY customer_id
  HAVING count(*) >= 2
),
city_stats AS (
  SELECT c.city,
         count(DISTINCT t.customer_id) AS customers,
         count(*) AS orders,
         sum(t.total) AS revenue,
         sum(t.total) FILTER (WHERE r.customer_id IS NOT NULL) AS repeat_revenue
  FROM order_totals t
  JOIN customers c ON c.id = t.customer_id
  LEFT JOIN repeat_customers r ON r.customer_id = t.customer_id
  GROUP BY c.city
)
SELECT city,
       customers,
       orders,
       revenue,
       round(revenue / orders, 2) AS avg_order,
       round(100.0 * coalesce(repeat_revenue, 0) / revenue, 1) AS repeat_pct
FROM city_stats
ORDER BY revenue DESC, city;
SQL
sudo -u postgres psql -d shop < ~/cte-demo/report_cte.sql

The October rule now lives in one place. A later step can read any earlier one: order_totals and repeat_customers both read october_orders. Steps are separated by commas, and only the first one has the word WITH. The FILTER (WHERE ...) clause sums only the rows that matched a repeat customer, which replaces the whole second branch of the nested version.

The two queries do the same work, but you no longer need to hold the inside-out shape in your head. You read it top to bottom, the same order PostgreSQL's data flows through it.

Check it worked

The output is the same four rows as before. Prove it by comparing the two outputs line by line:

Bash
diff <(sudo -u postgres psql -d shop < ~/cte-demo/report_nested.sql) \
     <(sudo -u postgres psql -d shop < ~/cte-demo/report_cte.sql) && echo "same output"

diff prints nothing and the shell prints same output. Any difference would be shown as lines marked < and >, which is a fast way to prove a refactor changed nothing before you replace a query in an application.

Step 4 · Check any step on its own

The real gain is debugging. To see what a step produces, keep the WITH list as it is and change only the final SELECT so it reads from that step. You can leave any step you are not checking in the list; it is not run unless something reads it.

Bash
cat > ~/cte-demo/check_steps.sql <<'SQL'
\set ON_ERROR_STOP on
WITH october_orders AS (
  SELECT id, customer_id
  FROM orders
  WHERE status = 'paid'
    AND ordered_on >= date '2026-10-01'
    AND ordered_on <  date '2026-11-01'
),
order_totals AS (
  SELECT o.id, o.customer_id, sum(i.qty * i.unit_price) AS total
  FROM october_orders o
  JOIN order_items i ON i.order_id = o.id
  GROUP BY o.id, o.customer_id
),
repeat_customers AS (
  SELECT customer_id
  FROM october_orders
  GROUP BY customer_id
  HAVING count(*) >= 2
)
SELECT (SELECT count(*) FROM october_orders)   AS october_orders,
       (SELECT count(*) FROM order_totals)     AS order_totals,
       (SELECT count(*) FROM repeat_customers) AS repeat_customers;
SQL
sudo -u postgres psql -d shop < ~/cte-demo/check_steps.sql
Text
 october_orders | order_totals | repeat_customers
----------------+--------------+------------------
            909 |          909 |              307
(1 row)

These counts are cheap sanity checks. order_totals must have exactly one row per October order, so the two first numbers must match. If they did not, a join would be duplicating or dropping orders, and you would know which step to look at.

To look at rows rather than counts, point the final SELECT at one step, for example SELECT * FROM order_totals ORDER BY id LIMIT 3;. The first three rows are orders 31, 32 and 33, worth 43600.00, 4250.00 and 1200.00.

Counting instead of printing every row also keeps the output short, which helps when you work over SSH on a slow or metered mobile connection.

Check it worked

Your output shows 909, 909 and 307. Try one change of your own: edit the final SELECT in check_steps.sql to SELECT * FROM repeat_customers ORDER BY customer_id LIMIT 5;, rerun the file, and you see five customer ids.

Step 5 · Choose between a CTE, a subquery and a view

All three name or wrap a query. They differ in how long they live and who can reuse them.

  • A subquery has no name you can reuse. It is fine for one small piece used once, such as WHERE id IN (SELECT ...).
  • A CTE has a name, but only inside one statement. It is the right tool for organising a single long query, as above. Nothing is stored in the database.
  • A view is a stored, named query. Any later query, any session and any user you grant access to can read it. PostgreSQL expands the view's query into the query that uses it, so a view costs nothing to keep and its result is always current.

When the same step turns up in several reports, such as "what each paid order was worth", promote it to a view. Create one without the October filter, so every report can bring its own date range:

Bash
sudo -u postgres psql -d shop <<'SQL'
CREATE VIEW paid_order_totals AS
SELECT o.id, o.customer_id, o.ordered_on, sum(i.qty * i.unit_price) AS total
FROM orders o
JOIN order_items i ON i.order_id = o.id
WHERE o.status = 'paid'
GROUP BY o.id, o.customer_id, o.ordered_on;

SELECT count(*) AS october_orders, sum(total) AS october_revenue
FROM paid_order_totals
WHERE ordered_on >= date '2026-10-01'
  AND ordered_on <  date '2026-11-01';
SQL

Inside a report, the view now stands in for the first two CTE steps: WITH order_totals AS (SELECT * FROM paid_order_totals WHERE ordered_on >= ...). Keep views for steps that several queries share. A view used by one report only is one more object to keep in step with the code.

Check it worked

The query returns 909 orders and revenue of 16393350.00, the sum of the four city revenues in the report. sudo -u postgres psql -d shop -c '\dv' lists paid_order_totals.

Step 6 · See when PostgreSQL inlines a CTE

Since PostgreSQL 12, a CTE that is a plain SELECT (no volatile functions, not recursive) and is referenced once is folded into the main query. The planner treats it as if you had written a subquery, so conditions from outside can reach inside it and use indexes. A CTE referenced two or more times is computed once by default and stored for the statement, which is called materialising it. Two keywords override the default: AS MATERIALIZED forces it to be computed separately, and AS NOT MATERIALIZED forces it to be folded in.

EXPLAIN (COSTS OFF) shows the plan without cost figures, which is easier to read. Compare a CTE read once, with and without MATERIALIZED:

Bash
sudo -u postgres psql -d shop <<'SQL'
EXPLAIN (COSTS OFF)
WITH all_orders AS (
  SELECT * FROM orders
)
SELECT * FROM all_orders WHERE id = 42;

EXPLAIN (COSTS OFF)
WITH all_orders AS MATERIALIZED (
  SELECT * FROM orders
)
SELECT * FROM all_orders WHERE id = 42;
SQL

The first plan is something like:

Text
 Index Scan using orders_pkey on orders
   Index Cond: (id = 42)

The CTE has disappeared. The id = 42 condition reached the table, and PostgreSQL looked up one row through the primary key index. The second plan is something like:

Text
 CTE Scan on all_orders
   Filter: (id = 42)
   CTE all_orders
     ->  Seq Scan on orders

Here PostgreSQL reads all 2,000 orders into a temporary result first, then scans that result for id 42. On a table with millions of rows that is the difference between a fraction of a millisecond and seconds.

Now a CTE read twice. It asks how many paid orders customers 42 and 43 placed:

Bash
sudo -u postgres psql -d shop <<'SQL'
EXPLAIN (COSTS OFF)
WITH paid AS (
  SELECT * FROM orders WHERE status = 'paid'
)
SELECT (SELECT count(*) FROM paid WHERE customer_id = 42) AS c42,
       (SELECT count(*) FROM paid WHERE customer_id = 43) AS c43;

EXPLAIN (COSTS OFF)
WITH paid AS NOT MATERIALIZED (
  SELECT * FROM orders WHERE status = 'paid'
)
SELECT (SELECT count(*) FROM paid WHERE customer_id = 42) AS c42,
       (SELECT count(*) FROM paid WHERE customer_id = 43) AS c43;
SQL

In the first plan you see a CTE paid section with a Seq Scan on orders, and two CTE Scan on paid lines: all paid orders are collected once, then filtered twice. In the second, there is no CTE Scan at all; each count looks up its customer through orders_customer_id_idx. Both versions return the same counts.

A rule of thumb that follows from this:

  • Leave the default alone in most queries. The planner usually picks well.
  • Add NOT MATERIALIZED when a CTE is read several times but each reader needs only a few of its rows, and an index could find them.
  • Add MATERIALIZED when a CTE does expensive work, such as calling a slow function per row, that you want done exactly once, or when you have measured that the folded plan is worse.
  • Check with EXPLAIN (ANALYZE) before and after, as in /tutorials/speed-up-slow-postgres-queries-with-explain. The keyword changes the plan, never the result.

Check it worked

Your first plan of each pair has no CTE Scan and the second has one, for the single-reference query; for the double-reference query, the default plan has two CTE Scan lines and the NOT MATERIALIZED plan has none. If the first plan shows Seq Scan on orders instead of an index scan, run sudo -u postgres psql -d shop -c 'ANALYZE;' and look again.

Step 7 · Move old rows to an archive in one statement

A CTE can also hold an INSERT, UPDATE or DELETE with a RETURNING clause. The rows it returns become a temporary result that the rest of the statement can read. That lets you delete rows from one table and insert them into another as a single statement: either both happen or neither does, and there is never a moment when an order is in both tables or in neither.

The shop wants September's cancelled orders, and their lines, out of the live tables. Create archive tables with the same columns:

Bash
sudo -u postgres psql -d shop <<'SQL'
CREATE TABLE orders_archive (LIKE orders INCLUDING ALL);
CREATE TABLE order_items_archive (LIKE order_items INCLUDING ALL);
SQL

LIKE ... INCLUDING ALL copies the columns, defaults, primary keys and other indexes, but not foreign keys, so the archive does not depend on the live tables.

Before you delete anything, preview how many rows the condition matches:

Bash
sudo -u postgres psql -d shop -c "SELECT count(*) FROM orders WHERE status = 'cancelled' AND ordered_on < date '2026-10-01';"

It matches 98 orders. Use exactly the same condition in the move. This statement deletes rows from the live orders table, and through ON DELETE CASCADE their lines in order_items, so on your own data run the preview first and take a backup as in /tutorials/back-up-and-restore-postgresql-with-pg-dump.

Bash
cat > ~/cte-demo/archive.sql <<'SQL'
\set ON_ERROR_STOP on
WITH moved_orders AS (
  DELETE FROM orders
  WHERE status = 'cancelled'
    AND ordered_on < date '2026-10-01'
  RETURNING id, customer_id, ordered_on, status
),
moved_items AS (
  INSERT INTO order_items_archive (order_id, line, product, qty, unit_price)
  SELECT i.order_id, i.line, i.product, i.qty, i.unit_price
  FROM order_items i
  JOIN moved_orders m ON m.id = i.order_id
  RETURNING order_id
),
archived_orders AS (
  INSERT INTO orders_archive (id, customer_id, ordered_on, status)
  SELECT id, customer_id, ordered_on, status
  FROM moved_orders
  RETURNING id
)
SELECT (SELECT count(*) FROM archived_orders) AS orders_moved,
       (SELECT count(*) FROM moved_items)     AS items_moved;
SQL
sudo -u postgres psql -d shop < ~/cte-demo/archive.sql
Text
 orders_moved | items_moved
--------------+-------------
           98 |         197
(1 row)

Three things make this work:

  • Every part of the statement sees the database as it was when the statement started. So moved_items can still read the lines of the orders being deleted, before the cascade removes them.
  • RETURNING is the only way one part passes rows to another. moved_items and archived_orders read moved_orders, never the orders table, to know what was deleted.
  • A data-modifying step always runs once and to the end, even if the final SELECT does not read it. That is different from a plain SELECT step, which runs only as far as something needs its rows.

Do not let two parts of one statement change the same row: PostgreSQL applies only one of the changes, and which one is hard to predict.

Check it worked

Bash
sudo -u postgres psql -d shop <<'SQL'
SELECT (SELECT count(*) FROM orders)              AS orders,
       (SELECT count(*) FROM order_items)         AS items,
       (SELECT count(*) FROM orders_archive)      AS orders_archived,
       (SELECT count(*) FROM order_items_archive) AS items_archived,
       (SELECT count(*) FROM orders
         WHERE status = 'cancelled' AND ordered_on < date '2026-10-01') AS left_behind;
SQL

You see 1902 orders and 3804 items left, 98 and 197 in the archive, and 0 September cancellations left behind: 2,000 and 4,001 before, exactly what moved. Run report_cte.sql again and the October report is unchanged, because it only ever counted paid orders.

Step 8 · Clean up

When you have finished, remove the practice database and folder. This deletes everything in shop, so check the name before you run it:

Bash
sudo -u postgres dropdb shop
rm -rf ~/cte-demo

Check it worked

Bash
sudo -u postgres psql -Atc "SELECT count(*) FROM pg_database WHERE datname = 'shop';"

The answer is 0, and ls ~/cte-demo reports that the folder does not exist.

Next steps

  • Answer ranking, running-total and month-over-month questions with window functions, which often sit in the last step of a CTE chain: /tutorials/answer-ranking-and-running-total-questions-with-sql-window-functions.
  • Walk trees and hierarchies with recursive CTEs: /tutorials/model-many-to-many-relationships-and-trees-in-sql.
  • Measure whether a rewrite made a query faster with EXPLAIN (ANALYZE): /tutorials/speed-up-slow-postgres-queries-with-explain.
  • Go back over grouping and filtering groups: /tutorials/summarise-data-with-group-by-and-having.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.