CodeBlanks Logo Icon CodeBlanks

What is a recursive CTE?

Learn the idea of a self-calling CTE.

What is a recursive CTE?

A recursive CTE is a CTE that references itself. Used for hierarchies and trees.

WITH RECURSIVE countdown(n) AS (
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM countdown WHERE n < 5
)
SELECT * FROM countdown;

This query counts from 1 to 5.

WITH RECURSIVE defines a self-referencing temporary result set (CTE) named countdown; the query after it uses it like a table. All columns are selected from countdown.

What is a recursive CTE? — details

A recursive CTE has an anchor and a recursive part. They are joined with UNION ALL.

It is used for tasks where you don't know the number of steps in advance, such as category trees, management chains or generating a sequence from 1 to N.

Practice What is a recursive CTE?

Write a RECURSIVE CTE that counts from 1 to 5.

Starter code

query.sql
-- recursive CTE
WITH RECURSIVE

Sample solution

query.sql
WITH RECURSIVE countdown(n) AS (
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM countdown WHERE n < 5
)
SELECT * FROM countdown;

Expected output

n
1
2
3
4
5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does a recursive CTE combine?

  • INTERSECT
  • JOIN
  • UNION ALL Correct answer
  • EXCEPT

Explanation: A recursive CTE combines with UNION ALL.

2 Add RECURSIVE

Question
WITH ____ countdown(n) AS (
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM countdown WHERE n < 5
)
SELECT * FROM countdown;
Answer
WITH RECURSIVE countdown(n) AS (
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM countdown WHERE n < 5
)
SELECT * FROM countdown;

Explanation: RECURSIVE is the right answer.

3 What is a recursive CTE: match the terms

Term Meaning
recursive recursive
anchor base
UNION ALL combine
hierarchy tree

All lessons in Advanced