Chaining Multiple CTEs for Modular Data Pipelines
Build multi-step SQL pipelines by chaining CTEs like staging transforms.
In plain words
Do a big calculation in small named steps, each using the result of the step before.
Think of it like…
An assembly line with labelled stations: wash, cut, assemble, inspect, pack. If the final product is wrong, you check each station's output in order until you find the one that went wrong.
Where you’ve seen it
A SaaS company's MRR movement report: latest_status keeps each subscription's current state per month, monthly_mrr sums MRR per customer per month, with_previous adds last month's MRR with LAG, movements labels each change as new, expansion, contraction or churn, and the final SELECT totals each movement per month. Each stage is a few lines and has one job.
Words you’ll hear
- CTE pipeline
- Several CTEs, each building on earlier ones, read top to bottom.
- Stage grain
- What one row of a stage represents, ideally noted in a comment.
- Inspection point
- Temporarily selecting from an intermediate CTE to check it.
- Promotion
- Turning a stage into a view, table or dbt model when it's reused or heavy.
Visual diagram
Theory & example queries
Designing the stages
Give each stage a single responsibility: filtering and cleaning, deduplicating, joining in lookups, aggregating to a new grain, or computing comparisons with window functions. Name it after what its rows are (paid_orders, customer_months), not after the step number. Write the grain in a comment above each CTE (-- one row per customer per month); when a later stage's numbers look wrong, the grain comments tell you where the multiplication happened.
A stage can read from any earlier stage, not just the previous one, so a final step can combine monthly_mrr with customers from much earlier. Keep filters as early as possible so later stages handle fewer rows, and keep presentation work (formatting, renaming, ORDER BY) in the final SELECT only.
WITH monthly_mrr AS ( SELECT customer_id, date_trunc('month', period_start) AS MONTH, SUM(mrr) AS mrr FROM subscription_periods WHERE status = 'active' GROUP BY 1, 2 ), with_previous AS ( SELECT *, LAG(mrr, 1, 0) OVER ( PARTITION BY customer_id ORDER BY MONTH ) AS prev_mrr FROM monthly_mrr ), movements AS ( SELECT MONTH, CASE WHEN prev_mrr = 0 THEN 'new' WHEN mrr > prev_mrr THEN 'expansion' WHEN mrr < prev_mrr THEN 'contraction' ELSE 'flat' END AS movement, mrr - prev_mrr AS delta FROM with_previous )SELECT MONTH, movement, SUM(delta)FROM movementsGROUP BY 1, 2ORDER BY 1, 2;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Expected output4 sample rows
| month | movement | sum |
|---|---|---|
| 2026-09-01 | expansion | 3200 |
| 2026-09-01 | flat | 0 |
| 2026-09-01 | new | 12500 |
| 2026-10-01 | contraction | -1800 |
Note: Illustrative MRR movements in currency units; the column label for the unaliased SUM is dialect-dependent.
(Churn needs a row for the month after the last active one, often from a date spine.)
Key takeaway: One job per stage, named for its rows, grain in a comment.
Testing, reuse and when to leave the query
To test a stage, swap the final SELECT for SELECT * FROM with_previous WHERE customer_id = 42 ORDER BY month and check one customer by hand, or SELECT COUNT(*), COUNT(DISTINCT (customer_id, month)) FROM monthly_mrr to confirm the grain. Because later stages depend on earlier ones, fix problems from the top down.
A CTE referenced twice in PostgreSQL 12+ is computed once and materialised by default; one referenced once is usually inlined into the plan. When a stage is expensive and needed by several reports, or would benefit from an index, promote it: a temporary table within a session, a view or materialised view in the database, or its own model in dbt. A pipeline that has grown past ten stages is often a sign some of them belong in shared models.
SELECT COUNT(*) AS rows, COUNT(DISTINCT (customer_id, MONTH)) AS keysFROM monthly_mrr;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output1 sample row
| rows | keys |
|---|---|
| 1452 | 1410 |
Note: Representative result showing 42 duplicate customer-month rows in the intermediate CTE.
If rows > keys, monthly_mrr isn't one row per customer per month.
Key takeaway: Inspect stages top-down; promote heavy, shared stages out of the query.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Write the stages in words
List the transformations before writing SQL: clean, aggregate to customer-month, compare with last month, label, total.
clean → aggregate → compare → label → total
When to use it & trade-offs
What it is
A CTE pipeline is a series of WITH steps where each step reads from the ones before it, like stages in a data pipeline: clean → deduplicate → enrich → aggregate → compare. Each step does one job, has a descriptive name and a known grain, and the final SELECT only presents the result. You can inspect any stage by pointing the final SELECT at it, which makes long analytical queries testable.
Why it matters: Real analytics questions, such as monthly recurring revenue movements, attribution or retention, need five or more transformations. Written as one nested query they're impossible to review; written as a named pipeline, a reviewer can check each stage's logic and grain in order. It's also how dbt models are structured, so the habit carries straight into data-engineering work.
When to reach for it
- MRR, retention, funnel and attribution reports
- Analyses that need several grains in sequence
- Queries other people will review
When to avoid or be careful
- Names like t1, t2, final2
- Stages that do several jobs at once
- Twenty-stage queries that should be shared models
A CTE pipeline vs nested subqueries vs separate models
Strengths: Readable top to bottom; each stage inspectable.
Watch out: Stages can't be shared with other queries or indexed.
Strengths: Compact.
Watch out: Read inside out; hard to test a single level.
Strengths: Shared, tested, documented; can be materialised.
Watch out: More objects to manage and deploy.
Interview signals & numbers to know
When this topic comes up
- “Walk me through how you'd structure this analysis”
- “This query is 300 lines; make it maintainable”
- dbt-style staging and marts
- MRR movements
- Testing SQL
Benchmarks & rules of thumb
- 1
- job per CTE
- PostgreSQL 12
- CTEs referenced once are inlined
- 2+ reports
- a sign a stage should become a model
Common mistakes & follow-ups
Common interview mistakes
- Aggregating to customer-month in one stage and accidentally re-joining raw rows later, multiplying the totals.
- Filtering in the final SELECT instead of the first stage, so every stage processes unneeded rows.
- Debugging the final numbers instead of checking each stage from the top.
Likely interviewer follow-ups
- How would you structure an MRR movement report in SQL?
- How do you test an intermediate step of a long query?
- When would you move a CTE into its own view or model?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Chaining Multiple CTEs for Modular Data Pipelines with hands-on SQL practice and interview Q&A.