Sub topic 3
Chaining several CTEs into a pipeline
A single CTE gives one intermediate result a name. Real reporting queries usually need several steps: aggregate, compare, filter, then format. This chapter shows how to list several CTEs in one WITH clause so that each step builds on the one before it.
What you should already know
This chapter assumes you can:
- write a single CTE with
WITH name AS (...)and select from it - use
GROUP BYwith aggregates such asSUMandAVG - read a basic window function call such as
LAG(...) OVER (ORDER BY ...)
The examples run on PostgreSQL. Other databases need small changes, which are noted where they matter.
The syntax for more than one CTE
Write WITH once. Then list each CTE as name AS (query), separated by commas. The main query follows the last CTE with no comma.
WITH step_one AS (
SELECT ...
),
step_two AS (
SELECT ... FROM step_one
),
step_three AS (
SELECT ... FROM step_two
)
SELECT ... FROM step_three;Three details cause most beginner errors:
WITHappears only once, before the first CTE.- A comma goes between CTEs.
- No comma goes after the last CTE.
A worked example: month-over-month change
The examples below use this small table. Run the setup first if you want to follow along.
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL,
order_date date NOT NULL,
amount numeric(10,2) NOT NULL
);
INSERT INTO orders (id, customer_id, order_date, amount) VALUES
(1, 1, DATE '2026-01-05', 100.00),
(2, 2, DATE '2026-01-20', 150.00),
(3, 1, DATE '2026-02-03', 300.00),
(4, 3, DATE '2026-02-14', 100.00),
(5, 2, DATE '2026-03-09', 150.00),
(6, 3, DATE '2026-03-21', 50.00);Suppose you want each month's revenue and how much it changed from the previous month. That takes two steps. First, total the orders by month. Second, put each month's revenue next to the previous month's.
WITH monthly_sales AS (
SELECT date_trunc('month', order_date) AS month,
SUM(amount) AS revenue
FROM orders
GROUP BY date_trunc('month', order_date)
),
with_prev AS (
SELECT month,
revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_revenue
FROM monthly_sales
)
SELECT month, revenue, revenue - prev_revenue AS change
FROM with_prev
ORDER BY month;With the sample data, the monthly totals are 250.00, 400.00, and 200.00. The query returns these rows (PostgreSQL shows month with a time part because date_trunc returns a timestamp):
| month | revenue | change |
|---|---|---|
| 2026-01-01 | 250.00 | NULL |
| 2026-02-01 | 400.00 | 150.00 |
| 2026-03-01 | 200.00 | -200.00 |
Read the query from top to bottom:
monthly_salesgroups the raw orders into one row per month.with_prevreads frommonthly_sales, not fromorders. It adds a column holding the previous month's revenue.- The final
SELECTreads fromwith_prevand subtracts.
January has no earlier month, so LAG returns NULL and the change is NULL as well. This is correct behavior, not a bug. If you need a number there, use COALESCE, but decide first whether "no previous month" should really count as zero.
Why chain instead of nesting
You can write the same logic with nested subqueries in the FROM clause:
SELECT month, revenue, revenue - prev_revenue AS change
FROM (
SELECT month,
revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_revenue
FROM (
SELECT date_trunc('month', order_date) AS month,
SUM(amount) AS revenue
FROM orders
GROUP BY date_trunc('month', order_date)
) AS monthly_sales
) AS with_prev
ORDER BY month;The result is identical. The difference is in how you read it. In the nested form, the first step you perform (the aggregation) sits at the bottom, inside two sets of parentheses. You read from the inside out. In the chained form, the steps appear in the order they happen, and each has a name that says what it does.
With a third or fourth step, the nested version becomes hard to follow. The chained version stays flat.
Splitting steps because SQL requires it
Sometimes you chain CTEs because the language forces a new layer, not for style. A common case: you cannot filter on a window function in the same SELECT where it is computed. Window functions are evaluated after WHERE, so this fails:
-- Fails: window functions are not allowed in WHERE
SELECT month, revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM monthly_sales
WHERE revenue - LAG(revenue) OVER (ORDER BY month) < 0;A new CTE layer fixes it. To find only the months where revenue fell, add a third step that filters the computed column:
WITH monthly_sales AS (
SELECT date_trunc('month', order_date) AS month,
SUM(amount) AS revenue
FROM orders
GROUP BY date_trunc('month', order_date)
),
with_prev AS (
SELECT month,
revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_revenue
FROM monthly_sales
),
with_change AS (
SELECT month,
revenue,
prev_revenue,
revenue - prev_revenue AS change,
ROUND(100.0 * (revenue - prev_revenue) / NULLIF(prev_revenue, 0), 1) AS pct_change
FROM with_prev
)
SELECT month, revenue, change, pct_change
FROM with_change
WHERE change < 0
ORDER BY month;For the sample data this returns one row: March 2026, revenue 200.00, change -200.00, pct_change -50.0.
Two things to notice:
- The
WHERE change < 0works becausechangeis now an ordinary column ofwith_change. It is not an alias defined in the sameSELECT. NULLIF(prev_revenue, 0)turns a zero divisor intoNULL, so the percentage isNULLinstead of raising a division-by-zero error.
A later CTE can use more than one earlier CTE
A pipeline does not have to be a straight line. A CTE can read from any CTE defined before it, and the final query can read from several. You can also reference one CTE more than once.
This query finds customers whose total spending is above the average customer total:
WITH customer_totals AS (
SELECT customer_id, SUM(amount) AS total
FROM orders
GROUP BY customer_id
),
overall AS (
SELECT AVG(total) AS avg_total
FROM customer_totals
)
SELECT ct.customer_id,
ct.total,
ROUND(o.avg_total, 2) AS avg_total
FROM customer_totals ct
CROSS JOIN overall o
WHERE ct.total > o.avg_total
ORDER BY ct.total DESC;The customer totals are 400.00, 300.00, and 150.00, so the average is about 283.33. The query returns customers 1 and 2.
customer_totals is used twice: once inside overall, and once in the final query. The name is written once and reused. With subqueries you would have to repeat the whole GROUP BY query. The CROSS JOIN is safe here because overall always has exactly one row.
Order matters: only earlier CTEs are visible
In a plain (non-recursive) WITH clause, a CTE can refer only to CTEs listed before it. It cannot refer to itself or to ones listed after. This fails in PostgreSQL:
WITH second_step AS (
SELECT * FROM first_step
),
first_step AS (
SELECT 1 AS n
)
SELECT * FROM second_step;PostgreSQL reports that the relation first_step does not exist. Move first_step above second_step and the query runs. The next chapter looks at visibility rules in more detail, and later chapters cover recursion, where a CTE does refer to itself.
Common errors in chained CTEs
| Symptom | Likely cause | Fix |
|---|---|---|
| Syntax error near `SELECT` after the last CTE | A trailing comma after the last CTE | Remove the comma before the final `SELECT` |
| Syntax error near `WITH` | `WITH` repeated before the second CTE | Write `WITH` once and separate CTEs with commas |
| Relation or table does not exist | The CTE is referenced before it is defined | Reorder so that each CTE comes after the ones it uses |
| Error that a CTE name is specified more than once | Two CTEs in one `WITH` share a name | Give each CTE a unique name |
| Column does not exist | The column was not selected or was renamed in an earlier CTE | Check the column list of the CTE you read from |
| Ambiguous column reference | Two joined CTEs both expose the same column name | Qualify the column with an alias, such as `ct.total` |
| Unexpected `NULL` in the first row | `LAG` has no previous row | Expected. Use `COALESCE` only if a default makes sense |
Debugging a pipeline one step at a time
A chained query is easy to check because every step is a complete query. When the output looks wrong, change only the last line. Replace the final SELECT with a query on an earlier step:
WITH monthly_sales AS (
SELECT date_trunc('month', order_date) AS month,
SUM(amount) AS revenue
FROM orders
GROUP BY date_trunc('month', order_date)
)
SELECT * FROM monthly_sales ORDER BY month;Check the rows each step produces, starting with the first. The first step whose output is wrong contains the bug. Nested subqueries are harder to debug this way, because you have to cut the inner query out of its parentheses first.
Naming and design guidelines
- Name each CTE for what it contains, such as
monthly_salesorcustomer_totals. Avoidt1,temp, andcte2. - Give each step one job. If a CTE aggregates, joins, and filters all at once, split it.
- List all needed columns in each step. Avoid
SELECT *in the middle of a pipeline, so that each step's output is clear. - Do not split steps that do not need splitting. A pipeline of eight trivial CTEs can be harder to read than one clear query.
Performance: chained does not mean cached
A chain of CTEs reads like a sequence of temporary tables, but it is not guaranteed to run that way. Depending on the database and its version, the engine may compute each CTE once and store it, or it may merge a CTE's query into the query that uses it. In PostgreSQL 12 and later, a CTE that is referenced once and has no side effects is generally inlined. A CTE referenced several times, such as customer_totals above, may be computed once and reused. A later chapter covers materialization and how to control it. For now, treat CTEs as a way to organize the query, not as a promise about how it runs.
Summary of the pattern
- Write
WITHonce, then separate CTEs with commas. - Put no comma after the last CTE.
- Each CTE can read from tables and from CTEs defined above it.
- Add a new CTE when you need to filter on a computed value, such as a window function result.
- Debug by selecting from an intermediate CTE in place of the final query.
Exercise
Using the orders table above, write a chained query with two CTEs. The first, customertotals, sums amount per customerid. The second, bigcustomers, keeps only customers whose total is at least 300. The final SELECT should return the customerid and total of the big customers, ordered by total descending. What rows does it return for the sample data?
Show answer
WITH customertotals AS ( SELECT customerid, SUM(amount) AS total FROM orders GROUP BY customerid ), bigcustomers AS ( SELECT customerid, total FROM customertotals WHERE total >= 300 ) SELECT customerid, total FROM bigcustomers ORDER BY total DESC; It returns customer 1 with total 400.00 and customer 2 with total 300.00. Customer 3 has 150.00 and is filtered out. The second CTE reads from customer_totals, not from orders.
Exercise
This query fails. Name the two mistakes and write the corrected query. WITH b AS ( SELECT n * 2 AS doubled FROM a ), WITH a AS ( SELECT 1 AS n ), SELECT doubled FROM b;
Show answer
The first mistake is that WITH is repeated before the second CTE. The second is the trailing comma after the last CTE. There is also an ordering problem: b reads from a, but a is defined after b, so a is not visible to b. The corrected query is: WITH a AS ( SELECT 1 AS n ), b AS ( SELECT n * 2 AS doubled FROM a ) SELECT doubled FROM b; It returns one row with the value 2.
Exercise
Why can't you write WHERE on a LAG(...) OVER (...) expression in the same SELECT that computes it, and how does a CTE solve this?
Show answer
Window functions are evaluated after the WHERE clause, so their results do not exist yet when WHERE runs. Computing the window value in one CTE turns it into an ordinary column. The next query layer, either another CTE or the final SELECT, can then filter on that column with WHERE.