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 66/ 160
04. Subqueries & Common Table Expressions (CTEs)

Introduction to Common Table Expressions (WITH Clause)

Name intermediate result sets with WITH for clearer analytical queries.

BeginnerWITH · Named Steps · Scope3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

A CTE lets you give a name to a mini-query and then use that name later in the same query.

Think of it like…

Showing your working in a maths exam: instead of one giant formula, you write "step 1 = …, step 2 = …, answer = …". Each named step is a CTE.

Where you’ve seen it

A monthly revenue report: one CTE filters paid orders, a second totals them per month, and the final SELECT computes month-over-month growth. Each step can be run and checked on its own while debugging.

Words you’ll hear

WITH clause
Defines one or more CTEs before the main statement.
Scope
A CTE exists only inside the statement that defines it.
Chained CTEs
Later CTEs can refer to earlier ones in the same WITH.
Materialization
Whether the database computes a CTE once and stores it, or inlines it into the main query.

Visual diagram

Loading interactive diagram

Theory & example queries

Writing and chaining CTEs

Start with WITH, give the CTE a name, and put its query in parentheses. Separate several CTEs with commas; each one can use the CTEs defined before it. The statement then ends with the main SELECT (or INSERT, UPDATE, DELETE) that uses them.

A CTE is a step inside one statement, not a saved object. It disappears when the statement finishes, unlike a view (saved in the schema) or a temporary table (lasts for the session).

Two chained CTEsQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  paid AS (3    SELECT4      *5    FROM6      orders7    WHERE8      status = 'paid'9  ),10  monthly AS (11    SELECT12      date_trunc('month', created_at) AS MONTH,13      SUM(amount) AS revenue14    FROM15      paid16    GROUP BY17      118  )19SELECT20  MONTH,21  revenue22FROM23  monthly24ORDER BY25  MONTH;
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/25
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative monthly revenue3 sample rows
Representative monthly revenue
monthrevenue
2026-09-0118420
2026-10-0123175
2026-11-0119640

Note: Illustrative totals from paid orders; actual month boundaries, currency units and rows depend on the source data and database date functions.

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

Key takeaway: Comma-separated, top to bottom, each step can use the ones above it.

Do CTEs make queries faster?

Usually not by themselves; they're mainly for readability. Since PostgreSQL 12, a non-recursive CTE that's referenced once is inlined into the main query and optimised as if you'd written a subquery. Before version 12, PostgreSQL always computed CTEs separately, which could block index use (an "optimization fence").

You can control this with WITH x AS MATERIALIZED (…) to compute it once (useful when it's referenced several times and is expensive) or AS NOT MATERIALIZED to force inlining. MySQL supports CTEs from version 8.0, SQL Server and Oracle have long supported them.

Forcing one computation in PostgreSQLQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sqlReadable preview
1WITH big2AS MATERIALIZED (3SELECT customer_id,4  SUM(amount)5AS total6FROM orders7GROUP BY 1)8SELECT …9FROM big a10JOIN big b ON …;
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/10
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative materialization behavior
CTE big: materialized once, then reused by both sides of the join Final columns and rows: depend on the omitted SELECT and ON clauses

Note: This teaching snippet deliberately uses ellipses and is not executable as written, so concrete result rows cannot be derived. EXPLAIN can confirm whether PostgreSQL materializes the CTE once.

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

Key takeaway: CTEs are for clarity; check the plan before assuming they change speed.

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 1Design

Break the problem into steps

Write the answer as a list of stages: filter the rows, aggregate them, then compare or rank.

Focus at this step

filter → aggregate → compare

What to watch at this step
One job
per CTE
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A Common Table Expression (CTE) is a named, temporary result set defined with WITH name AS (…) at the start of a query. The main query, and any later CTE in the same WITH, can then use it like a table. It exists only for that one statement.

Why it matters: CTEs turn a deeply nested query into readable, named steps, which makes complex analytics easier to write, review and debug. They're also the only way to write recursive queries in SQL, and interviewers expect you to structure multi-step answers with them.

When to reach for it

  • Analytics queries with several stages
  • Replacing deeply nested subqueries
  • Recursive queries (org charts, category trees) with WITH RECURSIVE

When to avoid or be careful

  • Assuming a CTE is cached and shared between statements; it isn't
  • Huge chains of CTEs that should really be a view or a data model
  • Expecting a CTE alone to make a slow query fast

CTE vs subquery vs view vs temp table

CTE
Best for: Multi-step logic inside one query; recursion

Strengths: Readable named steps that can be reused within the statement.

Watch out: Exists only for that statement.

Subquery
Best for: A short, one-off inner step

Strengths: Compact.

Watch out: Nested subqueries quickly become hard to read.

View / temp table
Best for: Logic reused across queries (view) or large intermediate results reused in a session (temp table)

Strengths: Shared or indexed.

Watch out: Extra objects to create, maintain and clean up.

Interview signals & numbers to know

When this topic comes up

  • “Make this query more readable”
  • “CTE vs subquery”
  • Multi-step analytics problems
  • WITH clause
  • Recursive query

Benchmarks & rules of thumb

1 statement -
the lifetime of a CTE
PostgreSQL 12 -
CTEs inlined by default from this version
MySQL 8.0 -
first MySQL version with CTEs

Common mistakes & follow-ups

Common interview mistakes

  • Trying to use a CTE in a second, separate statement.
  • Giving CTEs meaningless names like t1, t2, t3, which defeats the readability benefit.
  • Claiming CTEs are always materialized, or always faster, without checking the database version and plan.

Likely interviewer follow-ups

  • What is the difference between a CTE and a temporary table?
  • Does using a CTE improve performance? When could it make things worse?
  • How would you write a recursive CTE to list every employee under a manager?
Interview tip: In interviews, structure any multi-step answer as named CTEs and talk through each step. It's easier to follow, and interviewers can check your logic step by step.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Introduction to Common Table Expressions (WITH Clause) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Performance Trade-offs: Subqueries vs Joins
Next topic
Chaining Multiple CTEs for Modular Data Pipelines