Learn SQL
-- subqueries.cte_basics

CTEs — WITH … AS in SQL

Named subqueries that make complex logic readable

--concept

A Common Table Expression is a named subquery introduced with WITH name AS (…) that the rest of the statement can use like a temporary view. Instead of one giant nested expression you build readable layers: define dept_stats once, then join or filter against it. CTEs exist only for the duration of the statement, and multiple CTEs can chain comma-separated, each seeing the previous ones.

--how it works
1

Name the inner query

WITH dept_stats AS (SELECT department, AVG(salary) AS avg_sal FROM employees GROUP BY department) — the CTE computes once and behaves like a table for this statement.

2

Use it like a table

The main query joins employees to dept_stats on department — a completely ordinary join; nothing special remains about the CTE.

3

Filter against the computed column

WHERE e.salary > ds.avg_sal — each employee is compared to their own department average, computed in the layer below.

4

Chain layers with commas

WITH a AS (…), b AS (SELECT … FROM a WHERE …) — each CTE may reference the ones before it; complexity stays linear and readable.

5

It lives for one statement

The CTE exists only for this query — not stored, not shareable. Need it across queries? That is a view (next topic).

--visualization
employees eAlice · Engi85kBob · Sale52kCynthia · Engi91kDavid · Mark47kElena · Sale58kFarid · Engi73kWITH dept_stats AS (…)Engineeringavg_sal83kSalesavg_sal55kMarketingavg_sal47klives only for this statementjoin next…result — above avgAliceEngineering avg 83k85kCynthiaEngineering avg 83k91kElenaSales avg 55k58kDavid sits exactly at his average — > excludes himWHERE e.salary > ds.avg_sal — layered, readable SQL
CTE dept_stats join lines
Stage 1 / 5
WITH dept_stats AS (SELECT department, AVG(salary) … GROUP BY department) — a named subquery, built first.
--example
query.sql
1WITH dept_stats AS (
2 SELECT department, AVG(salary) AS avg_sal
3 FROM employees GROUP BY department
4)
5SELECT e.name, e.department, e.salary
6FROM employees e
7JOIN dept_stats ds ON e.department = ds.department
8WHERE e.salary > ds.avg_sal;
Result
namedepartmentsalary
AliceEngineering85000
CynthiaEngineering91000
ElenaSales58000

dept_stats holds each department’s average (83,000 / 55,000 / 47,000). Joining employees to it and keeping above-average earners gives Alice and Cynthia (Engineering, avg 83k) plus Elena (Sales, avg 55k). David sits exactly at his department’s average, so > excludes him.

--variants

Above department average

The flagship CTE query: compute per-group stats, then join and filter.

query.sql
1WITH dept_stats AS (
2 SELECT department, AVG(salary) AS avg_sal
3 FROM employees GROUP BY department
4)
5SELECT e.name, e.department, e.salary
6FROM employees e
7JOIN dept_stats ds ON e.department = ds.department
8WHERE e.salary > ds.avg_sal;
Result
namedepartmentsalary
AliceEngineering85000
CynthiaEngineering91000
ElenaSales58000
1dept_stats: Engineering 83,000 · Sales 55,000 · Marketing 47,000.
2The join attaches each employee’s department average to their row.
3Above-average survivors: Alice and Cynthia (Engineering), Elena (Sales). David sits exactly at 47,000, and > excludes ties.

Chained CTEs — layers on layers

Each named step does one thing; the next step builds on it.

query.sql
1WITH eng AS (
2 SELECT * FROM employees WHERE department = 'Engineering'
3),
4rich_eng AS (
5 SELECT * FROM eng WHERE salary > 80000
6)
7SELECT name, salary FROM rich_eng ORDER BY salary DESC;
Result
namesalary
Cynthia91000
Alice85000
1eng narrows to the three engineers.
2rich_eng filters that to the two above 80,000 — referencing eng, not the base table.
3The final SELECT is trivial. Read top to bottom like a recipe; each layer is independently testable.

CTE referenced twice — no subquery duplication

Name it once, use it twice — impossible with a bare subquery.

query.sql
1WITH stats AS (
2 SELECT MIN(salary) AS lo, MAX(salary) AS hi FROM employees
3)
4SELECT e.name, e.salary
5FROM employees e, stats
6WHERE e.salary = stats.lo OR e.salary = stats.hi;
Result
namesalary
Cynthia91000
David47000
1A subquery would have to repeat the aggregate expression twice; the CTE names it once.
2The cross join against a one-row CTE is a convenient way to make its columns available.
3Cynthia holds the max (91,000), David the min (47,000) — the payroll extremes.

Same query without the CTE

What the WITH clause buys you is readability, not power.

query.sql
1SELECT e.name, e.department, e.salary
2FROM employees e
3JOIN (SELECT department, AVG(salary) AS avg_sal FROM employees GROUP BY department) ds
4 ON e.department = ds.department
5WHERE e.salary > ds.avg_sal;
Result
namedepartmentsalary
AliceEngineering85000
CynthiaEngineering91000
ElenaSales58000
1Identical result rows to the CTE version — the engine may even produce the identical plan.
2With one level the subquery is fine; at three levels of nesting the CTE form wins decisively.
3Choose CTEs for people, subqueries for one-liners.
--key facts
Readability firstthe #1 benefit — each WITH layer does one understandable thing
Materialisation variessome engines compute a CTE once, others inline it like a view — EXPLAIN tells you
RECURSIVE existsWITH RECURSIVE lets a CTE reference itself — org charts, graphs, bill-of-materials
--use cases
Multi-step analytics: filter → aggregate → rank, each step a named CTE
Per-group comparisons (above department average) without correlated subqueries
Reusing the same intermediate result twice in one query
Making monster report queries reviewable — one concern per line of WITH
--under the hood
Engines differ on materialisation: Postgres ≥12 inlines simple CTEs, and MATERIALIZED forces the old once-computed behaviour.
Recursive CTEs (next module topic) extend the same syntax with self-reference for hierarchies.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.