Reading history

SQL Common Table Expressions (WITH and Recursive CTE)

5 min read 0 views

Learn SQL CTEs with the WITH clause: readable multi-step queries, several CTEs in one query, and recursive CTEs for hierarchies and number sequences.

A Common Table Expression (CTE) is a named, temporary result defined with the WITH keyword at the start of a query. It lets you break a complicated query into readable steps, each with a meaningful name, instead of nesting subqueries inside each other. A recursive CTE goes further and can walk hierarchies such as organisation charts, category trees or folder structures.

In this lesson you will learn

  • The WITH name AS (...) syntax
  • How a CTE replaces a nested subquery
  • Defining several CTEs in one query
  • Recursive CTEs: anchor member, recursive member and stop condition
  • When to choose a CTE, a subquery or a view

A First CTE

Question: which students score above their own department’s average?

-- A CTE names a temporary result you can use like a table
WITH dept_avg AS (
    SELECT dept, ROUND(AVG(cgpa), 2) AS avg_cgpa
    FROM students
    GROUP BY dept
)
SELECT s.name, s.dept, s.cgpa, d.avg_cgpa
FROM students AS s
JOIN dept_avg AS d ON d.dept = s.dept
WHERE s.cgpa > d.avg_cgpa
ORDER BY s.dept, s.cgpa DESC;

Output

+--------+------+------+----------+
| name   | dept | cgpa | avg_cgpa |
+--------+------+------+----------+
| Sabbir | BBA  | 3.55 | 3.33     |
| Tania  | CSE  | 3.95 | 3.81     |
| Nusrat | CSE  | 3.82 | 3.81     |
| Arif   | EEE  | 3.41 | 3.2      |
+--------+------+------+----------+
(4 rows)
  • WITH dept_avg AS (...) defines a result named dept_avg with one row per department.
  • The main query then joins to dept_avg exactly as if it were a table.
  • The CTE exists only for this one statement. Unlike a view, nothing is saved in the database.
  • The same result is possible with a subquery in FROM, but the CTE puts the step first and gives it a name, so the query reads from top to bottom.

Several CTEs in One Query

WITH delivered AS (
    SELECT customer, amount FROM orders WHERE status = 'delivered'
),
per_customer AS (
    SELECT customer, SUM(amount) AS total FROM delivered GROUP BY customer
)
SELECT customer, total
FROM per_customer
WHERE total > 1000
ORDER BY total DESC;

Separate the CTEs with commas and write WITH only once. Each CTE can use the ones defined before it, so the query becomes a short pipeline: filter, then total, then select.

Recursive CTEs

The employees table stores each person’s manager_id. A recursive CTE follows these links level by level.

-- Recursive CTE: walk the management chain from the CEO down
WITH RECURSIVE chain AS (
    SELECT id, name, title, manager_id, 0 AS level
    FROM employees
    WHERE manager_id IS NULL
    UNION ALL
    SELECT e.id, e.name, e.title, e.manager_id, c.level + 1
    FROM employees AS e
    JOIN chain AS c ON e.manager_id = c.id
)
SELECT level, name, title FROM chain ORDER BY level, name;

-- Recursive CTE as a number generator
WITH RECURSIVE n(x) AS (SELECT 1 UNION ALL SELECT x + 1 FROM n WHERE x < 5)
SELECT x, x * x AS square FROM n;

Output

+-------+---------+------------+
| level | name    | title      |
+-------+---------+------------+
| 0     | Shahana | CEO        |
| 1     | Faisal  | CTO        |
| 1     | Lipi    | CFO        |
| 2     | Anik    | Accountant |
| 2     | Mou     | Engineer   |
| 2     | Rubel   | Engineer   |
| 3     | Sumi    | Intern     |
+-------+---------+------------+
(7 rows)

+---+--------+
| x | square |
+---+--------+
| 1 | 1      |
| 2 | 4      |
| 3 | 9      |
| 4 | 16     |
| 5 | 25     |
+---+--------+
(5 rows)
  • A recursive CTE has two parts joined by UNION ALL:
    • the anchor member runs once and gives the starting rows (here the CEO, who has no manager);
    • the recursive member refers to the CTE itself and finds the next level (everyone whose manager is in the previous level).
  • The process repeats until the recursive member returns no new rows. The level column counts how deep each person is.
  • The second example generates numbers 1 to 5. The condition WHERE x < 5 is the stop condition; without it the query would run forever.
  • PostgreSQL, MySQL 8 and SQLite require the word RECURSIVE; SQL Server and Oracle accept a plain WITH.

CTE, Subquery or View?

ToolLifetimeBest for
SubqueryOne expressionA small, one-off filter or value
CTEOne statementMulti-step logic, reuse within a query, recursion
ViewSaved in the databaseLogic shared across many queries and users

Common Mistakes

  1. Writing WITH before every CTE instead of separating them with commas.
  2. Missing stop condition in a recursive CTE, causing an endless loop. Cycles in the data (A manages B, B manages A) cause the same problem.
  3. Using UNION instead of UNION ALL in recursion without a reason; it adds duplicate checks at every step.
  4. Expecting a CTE to persist into the next statement.

Practice Exercises

Exercise 1. Using a CTE, list departments whose average CGPA is above 3.3.

Show answer
WITH d AS (
    SELECT dept, AVG(cgpa) AS avg_cgpa FROM students GROUP BY dept
)
SELECT dept, ROUND(avg_cgpa, 2) AS avg_cgpa FROM d WHERE avg_cgpa > 3.3;

It returns BBA (3.33) and CSE (3.81).

Exercise 2. Write a recursive CTE that lists everyone who reports to Faisal, directly or indirectly.

Show answer
WITH RECURSIVE team AS (
    SELECT id, name FROM employees WHERE manager_id = 2
    UNION ALL
    SELECT e.id, e.name FROM employees AS e JOIN team AS t ON e.manager_id = t.id
)
SELECT name FROM team;

It returns Rubel, Mou and Sumi.

Frequently Asked Questions

Are CTEs faster than subqueries?

Usually they perform the same, because most optimisers treat a simple CTE like a subquery. Their main benefit is readability. Some databases can store (materialise) a CTE’s result when it is used several times.

Can I use a CTE with INSERT, UPDATE or DELETE?

Yes, in most databases. The WITH clause comes before the statement, for example WITH old AS (...) DELETE FROM orders WHERE id IN (SELECT id FROM old).

Summary

  • WITH name AS (query) creates a temporary named result for one statement.
  • Chain several CTEs with commas to build readable step-by-step queries.
  • Recursive CTEs use an anchor, a recursive member and a stop condition.
  • They are ideal for hierarchies and generated sequences.

Next: SQL Window Functions.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *