Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

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
Data Science topics
Lesson 27/ 160
02. SQL & Data Engineering Basics

Common Table Expressions (CTEs)

Break complex logic into readable WITH clauses, including recursive hierarchy queries.

IntermediateWITH Clause · Readable SQL3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A CTE gives a name to a step of your query so you can build a big result from small, understandable pieces.

Think of it like…

A recipe written as numbered prep steps (chop onions, make the sauce, cook the pasta, combine) instead of one giant paragraph. You can taste after each step, and a colleague can follow it.

Where you’ve seen it

A churn feature query has five CTEs: base (one row per customer at the snapshot date), orders_90d (aggregated order features), tickets_90d (support features), labels (churned within 30 days after the snapshot) and a final SELECT joining them all. Each CTE has a comment stating its grain, and the analyst checks SELECT COUNT(*), COUNT(DISTINCT customer_id) on each; the check on tickets_90d shows 1.4 million rows for 1.2 million customers, revealing a missing aggregation before it corrupted the model.

Words you’ll hear

WITH clause
Defines one or more named CTEs before the main SELECT.
Stage grain
What one row of the CTE represents, ideally written as a comment.
Recursive CTE
A CTE with an anchor query and a recursive member that references itself.
Materialisation
Whether the database computes a CTE once and stores it or inlines it into the plan.

Visual diagram

Loading interactive diagram

Theory & deep dive

Structuring queries with CTEs

Define CTEs top to bottom in the order you'd explain the logic, name them after what their rows are (orders_90d, not t2), and keep each stage small and single-purpose. Multiple CTEs are separated by commas after one WITH; a CTE can read any earlier CTE. Filter early (in the first stages) so later stages process less data, put date logic in one place (a params CTE with snapshot_date and horizon_days), and finish with a simple final SELECT.

Test as you build: run the query ending at each stage, check COUNT(*) and COUNT(DISTINCT key), and compare totals with raw tables. In PostgreSQL 12+ a CTE referenced once is inlined; one referenced twice is computed once (MATERIALIZED and NOT MATERIALIZED override this). Other engines vary: SQL Server re-evaluates CTEs each time they're referenced, so for expensive reused stages use a temporary table.

A parameters CTE for reproducible snapshots

WITH params AS (SELECT DATE '2026-09-30' AS snap, 90 AS lookback_days, 30 AS horizon_days), orders_90d AS (SELECT o.customer_id, COUNT(*) AS orders, SUM(o.amount) AS spend FROM orders o, params p WHERE o.created_at >= p.snap - p.lookback_days AND o.created_at < p.snap GROUP BY 1) SELECT * FROM orders_90d; Features use only data before the snapshot.

Key takeaway: Small named stages, a params CTE, and a check after each stage.

Recursive CTEs and where CTEs stop being enough

A recursive CTE has an anchor (SELECT employee_id, manager_id, 0 AS depth FROM employees WHERE manager_id IS NULL) and a recursive member that joins the previous result (... JOIN org o ON e.manager_id = o.employee_id), combined with UNION ALL. It's used for org charts, category trees, bill-of-materials and graph walks. Include a depth counter or a path array to stop cycles, and note that engines limit recursion depth (SQL Server 100 by default, MySQL 1,000).

CTEs organise one query, but they don't persist. When a stage is expensive, shared by several queries, or needs indexes, materialise it as a table or view, or move the logic into a dbt model with tests, and keep the final training table versioned with its snapshot date. For very long pipelines, split them into several models rather than one 500-line query. In pandas the same idea is a chain of named DataFrames or a pipeline of functions.

Depth of everyone in an org chart

WITH RECURSIVE org AS (SELECT employee_id, manager_id, 0 AS depth FROM employees WHERE manager_id IS NULL UNION ALL SELECT e.employee_id, e.manager_id, o.depth + 1 FROM employees e JOIN org o ON e.manager_id = o.employee_id) SELECT * FROM org;

Key takeaway: Recursion for hierarchies; persist shared or expensive stages outside the query.

How it works, step by step

Step 1 of 4
Design

1. Sketch the stages

List the stages and their grains before writing SQL: base, feature groups, labels, final join.

base → orders_90d → tickets_90d → labels
Key numbers at this step
One job
per stage

When to use it & trade-offs

What it is

A CTE (common table expression) is a named, temporary result defined with WITH name AS (SELECT …) that later steps can read, so a long query becomes a short pipeline of named stages: clean → aggregate → join → label. A recursive CTE repeatedly joins to its own output to walk hierarchies such as org charts or category trees. For data scientists CTEs are how you build feature and label tables that other people can read, test stage by stage and reproduce.

Why it matters: Feature queries grow to hundreds of lines. Written as nested subqueries they can't be debugged; written as CTEs, you can run each stage's SELECT * FROM stage LIMIT 20 and check row counts, which is exactly how bugs like duplicated keys or leaking joins are found. The same structure maps onto dbt models and pandas pipelines, so it's also how analytics code is organised in teams.

When to reach for it

  • Feature and label tables for models
  • Cohort and funnel logic
  • Hierarchy walks with recursion

When to avoid or be careful

  • Stages named t1, t2, t3
  • Recursive CTEs with no depth or cycle protection
  • Assuming a CTE is computed once in every database

Structuring complex SQL

CTE pipeline in one query
Best for: One analysis or feature table

Strengths: Readable; stage-by-stage debugging.

Watch out: Not reusable by other queries.

Nested subqueries
Best for: One or two simple levels

Strengths: Compact.

Watch out: Hard to read and test.

Temp tables / views / dbt models
Best for: Shared or expensive stages

Strengths: Reusable; indexable; versionable.

Watch out: More objects to manage.

Interview signals & numbers to know

When this topic comes up

  • “Make this 400-line query readable”
  • “Build a training table with a snapshot date”
  • “Traverse a hierarchy in SQL”
  • dbt-style models
  • Debugging joins

Benchmarks & rules of thumb

1 job -
per CTE stage
PostgreSQL 12 -
CTEs referenced once are inlined
100 / 1,000 -
default recursion limits in SQL Server / MySQL

Common mistakes & follow-ups

Common interview mistakes

  • Joining two feature stages that weren't aggregated to one row per customer, duplicating training rows.
  • Computing features with data after the snapshot date and leaking the label.
  • Writing a recursive CTE over a graph with cycles and no stop condition.

Likely interviewer follow-ups

  • How would you structure the query that builds a churn training table?
  • How do you debug a long CTE query?
  • When would you stop using CTEs and create a table?
Interview tip: Describe checking COUNT and COUNT DISTINCT after each stage. It shows how you catch grain mistakes before they reach a model.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Common Table Expressions (CTEs) with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
Subqueries & Nested Queries
Next topic
Window Functions (ROW_NUMBER, RANK, DENSE_RANK)