Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 67/ 160
04. Subqueries & Common Table Expressions (CTEs)

Chaining Multiple CTEs for Modular Data Pipelines

Build multi-step SQL pipelines by chaining CTEs like staging transforms.

IntermediateCTE Pipeline · Modular Steps3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

The first three stagesQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  monthly_mrr AS (3    SELECT4      customer_id,5      date_trunc('month', period_start) AS MONTH,6      SUM(mrr) AS mrr7    FROM8      subscription_periods9    WHERE10      status = 'active'11    GROUP BY12      1,13      214  ),15  with_previous AS (16    SELECT17      *,18      LAG(mrr, 1, 0) OVER (19        PARTITION BY20          customer_id21        ORDER BY22          MONTH23      ) AS prev_mrr24    FROM25      monthly_mrr26  ),27  movements AS (28    SELECT29      MONTH,30      CASE31        WHEN prev_mrr = 0 THEN 'new'32        WHEN mrr > prev_mrr THEN 'expansion'33        WHEN mrr < prev_mrr THEN 'contraction'34        ELSE 'flat'35      END AS movement,36      mrr - prev_mrr AS delta37    FROM38      with_previous39  )40SELECT41  MONTH,42  movement,43  SUM(delta)44FROM45  movements46GROUP BY47  1,48  249ORDER BY50  1,51  2;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/51
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
monthmovementsum
2026-09-01expansion3200
2026-09-01flat0
2026-09-01new12500
2026-10-01contraction-1800

Note: Illustrative MRR movements in currency units; the column label for the unaliased SUM is dialect-dependent.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

(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.

A grain check on one stageQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  COUNT(*) AS rows,3  COUNT(DISTINCT (customer_id, MONTH)) AS keys4FROM5  monthly_mrr;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/5
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output1 sample row
Expected output
rowskeys
14521410

Note: Representative result showing 42 duplicate customer-month rows in the intermediate CTE.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Plan

Write the stages in words

List the transformations before writing SQL: clean, aggregate to customer-month, compare with last month, label, total.

Focus at this step

clean → aggregate → compare → label → total

What to watch at this step
Stages
4–8 typical
Tip: use ← → to move between steps

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

Chained CTEs in one query
Best for: One analysis with several transformation steps

Strengths: Readable top to bottom; each stage inspectable.

Watch out: Stages can't be shared with other queries or indexed.

Nested subqueries
Best for: One or two simple levels

Strengths: Compact.

Watch out: Read inside out; hard to test a single level.

Separate views or dbt models
Best for: Stages reused across reports

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?
Interview tip: Talk through the stages and the grain of each before writing SQL. Interviewers care more about a clear pipeline than about any single clever step.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Introduction to Common Table Expressions (WITH Clause)
Next topic
Refactoring Deeply Nested Subqueries into Readable CTEs