LearnFrenzy
Sign in Take a free test

CTEs and Window Functions · Lesson 19 of 30

SQL CTE: WITH Clause and Recursive CTEs

6 min read Updated Nov 7, 2026 Saurabh Samir

As questions get harder, queries with nested subqueries become hard to read – you have to start in the middle and work outwards. A common table expression (CTE) lets you name each step with WITH and write the query top to bottom, like a recipe. Recursive CTEs go further: they can walk an org chart or generate a series of dates.

In this lesson

  • Writing a CTE with WITH
  • Chaining several CTEs
  • Recursive CTEs for hierarchies
  • Generating number and date series

Your first CTE

WITH order_totals AS (
  SELECT order_id, SUM(quantity * unit_price) AS total
  FROM order_items
  GROUP BY order_id
)
SELECT order_id, total
FROM order_totals
WHERE total > (SELECT AVG(total) FROM order_totals)
ORDER BY total DESC;

Output

+----------+---------+
| order_id | total   |
+----------+---------+
|      105 | 3697.00 |
|      102 | 2499.00 |
|      111 | 2098.00 |
|      104 | 1499.00 |
+----------+---------+

order_totals behaves like a temporary table that exists only for this statement – and unlike a derived table, it can be referenced more than once (here, twice).

Chaining CTEs: a step-by-step report

WITH delivered AS (                         -- step 1: only delivered orders
  SELECT order_id, customer_id FROM orders WHERE status = 'delivered'
),
spend AS (                                  -- step 2: spend per customer
  SELECT d.customer_id, SUM(i.quantity * i.unit_price) AS spent
  FROM delivered d
  JOIN order_items i ON i.order_id = d.order_id
  GROUP BY d.customer_id
),
ranked AS (                                 -- step 3: label the customers
  SELECT customer_id, spent,
         CASE WHEN spent >= 3000 THEN 'Gold' WHEN spent >= 1000 THEN 'Silver' ELSE 'Bronze' END AS tier
  FROM spend
)
SELECT c.name, r.spent, r.tier
FROM ranked r
JOIN customers c ON c.customer_id = r.customer_id
ORDER BY r.spent DESC;

Output

+------------+---------+--------+
| name       | spent   | tier   |
+------------+---------+--------+
| Ravi Kumar | 3798.00 | Gold   |
| Kiran Rao  | 3697.00 | Gold   |
| Asha Verma | 1639.00 | Silver |
| Meera Nair | 1000.00 | Silver |
| Neha Gupta |  700.00 | Bronze |
+------------+---------+--------+

Reading a chained CTE

  1. deliveredfilter the orders
  2. spenduses delivered: total per customer
  3. rankeduses spend: assign a tier
  4. final SELECTadds customer names

Each step can use the ones defined before it. You can test a step on its own by temporarily selecting from it – a big help when debugging long reports.

Recursive CTEs: walking a hierarchy

A recursive CTE has two parts joined by UNION ALL: an anchor (the starting rows) and a recursive part that refers to the CTE itself, adding one level at a time until no new rows appear.

WITH RECURSIVE org AS (
  SELECT emp_id, name, manager_id, 1 AS level, CAST(name AS CHAR(200)) AS path
  FROM employees
  WHERE manager_id IS NULL                              -- anchor: the CEO
  UNION ALL
  SELECT e.emp_id, e.name, e.manager_id, org.level + 1, CONCAT(org.path, ' > ', e.name)
  FROM employees e
  JOIN org ON e.manager_id = org.emp_id                 -- recursive part: their reports
)
SELECT level, CONCAT(REPEAT('    ', level - 1), name) AS org_chart, path
FROM org
ORDER BY path;

Output

+-------+----------------------+------------------------------------------+
| level | org_chart            | path                                     |
+-------+----------------------+------------------------------------------+
|     1 | Anita Desai          | Anita Desai                              |
|     2 |     Farhan Ali       | Anita Desai > Farhan Ali                 |
|     3 |         Lata Joshi   | Anita Desai > Farhan Ali > Lata Joshi    |
|     3 |         Tom Mathew   | Anita Desai > Farhan Ali > Tom Mathew    |
|     2 |     Kavya Reddy      | Anita Desai > Kavya Reddy                |
|     3 |         Imran Shaikh | Anita Desai > Kavya Reddy > Imran Shaikh |
|     2 |     Rohit Mehta      | Anita Desai > Rohit Mehta                |
|     3 |         Dev Patel    | Anita Desai > Rohit Mehta > Dev Patel    |
|     3 |         Priya Sharma | Anita Desai > Rohit Mehta > Priya Sharma |
|     3 |         Sana Iqbal   | Anita Desai > Rohit Mehta > Sana Iqbal   |
+-------+----------------------+------------------------------------------+

How the recursion runs

  1. Anchorlevel 1: Anita
  2. Iteration 1employees whose manager is Anita → Rohit, Farhan, Kavya (level 2)
  3. Iteration 2their reports → Sana, Dev, Priya, Lata, Tom, Imran (level 3)
  4. Iteration 3no new rows → stop

Stopping and types

  • The recursive part must eventually return no rows, or MySQL stops it at cte_max_recursion_depth (1000) with an error.
  • The anchor decides column types – that's why path is cast to a wide CHAR(200); otherwise longer paths would be cut off.

All reports under a manager

WITH RECURSIVE team AS (
  SELECT emp_id, name FROM employees WHERE name = 'Rohit Mehta'
  UNION ALL
  SELECT e.emp_id, e.name FROM employees e JOIN team t ON e.manager_id = t.emp_id
)
SELECT name FROM team WHERE name <> 'Rohit Mehta' ORDER BY name;

Output

+--------------+
| name         |
+--------------+
| Dev Patel    |
| Priya Sharma |
| Sana Iqbal   |
+--------------+

Generating series

Reports often need a row for every day or number – even when there's no data for it. A recursive CTE generates the series, and a LEFT JOIN fills in the data:

WITH RECURSIVE days AS (
  SELECT DATE('2025-11-01') AS day
  UNION ALL
  SELECT day + INTERVAL 1 DAY FROM days WHERE day < '2025-11-07'
)
SELECT d.day, DAYNAME(d.day) AS weekday, COUNT(o.order_id) AS orders
FROM days d
LEFT JOIN orders o ON o.order_date = d.day
GROUP BY d.day
ORDER BY d.day;

Output

+------------+-----------+--------+
| day        | weekday   | orders |
+------------+-----------+--------+
| 2025-11-01 | Saturday  |      0 |
| 2025-11-02 | Sunday    |      1 |
| 2025-11-03 | Monday    |      0 |
| 2025-11-04 | Tuesday   |      0 |
| 2025-11-05 | Wednesday |      1 |
| 2025-11-06 | Thursday  |      1 |
| 2025-11-07 | Friday    |      0 |
+------------+-----------+--------+

Without the generated days, days with no orders would simply be missing from the report – and charts would quietly skip them.

Practice

Try it yourself

  1. Using a CTE, list departments whose average salary is above the company average.

    Show solution
    WITH dept AS (
      SELECT department, AVG(salary) AS avg_salary FROM employees GROUP BY department
    )
    SELECT department, ROUND(avg_salary) AS avg_salary
    FROM dept
    WHERE avg_salary > (SELECT AVG(salary) FROM employees)
    ORDER BY avg_salary DESC;

    Output

    +-------------+------------+
    | department  | avg_salary |
    +-------------+------------+
    | Management  |     250000 |
    | Engineering |     128750 |
    +-------------+------------+
  2. Generate the numbers 1 to 5 and their squares with a recursive CTE.

    Show solution
    WITH RECURSIVE n AS (
      SELECT 1 AS x
      UNION ALL
      SELECT x + 1 FROM n WHERE x < 5
    )
    SELECT x, x * x AS square FROM n;

    Output

    +------+--------+
    | x    | square |
    +------+--------+
    |    1 |      1 |
    |    2 |      4 |
    |    3 |      9 |
    |    4 |     16 |
    |    5 |     25 |
    +------+--------+

Quick check

What does a CTE give you over a derived table?

A name you can reference several times, and top-to-bottom readability; it can also be recursive.

What are the two parts of a recursive CTE?

An anchor query and a recursive query that references the CTE, joined with UNION ALL.

What stops a recursive CTE?

The recursive part returning no new rows (or hitting the maximum recursion depth).

Summary

  • WITH names query steps; chain CTEs to build complex reports readably.
  • Recursive CTEs (anchor UNION ALL recursive part) walk hierarchies level by level.
  • Generate date and number series with recursive CTEs, then LEFT JOIN data onto them.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links