CodeBlanks Logo Icon CodeBlanks

Anchor and recursive parts

Learn the two parts joined by UNION ALL.

Anchor and recursive

The anchor is the starting point, the recursive part calls itself.

-- anchor: SELECT 1
-- recursive: SELECT n + 1 FROM countdown WHERE n < 5

Anchor is base, recursive is step.

Anchor and recursive — details

The anchor gives a fixed result. The recursive part builds on the previous step. Results merge with UNION ALL.

Each round only processes the rows produced by the previous round; recursion stops on its own in the first round that produces no new rows.

Practice Anchor and recursive

Write a recursive CTE: anchor SELECT 1, recursive SELECT n+1 ... WHERE n < 5.

Starter code

query.sql
-- anchor and recursive
WITH RECURSIVE countdown(n) AS (
  SELECT 1

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 Add UNION ALL

Question
  SELECT 1
  ____
  SELECT n + 1 FROM countdown WHERE n < 5
Answer
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM countdown WHERE n < 5

Explanation: UNION ALL is the right answer.

2 What does the anchor do?

  • The result
  • Sorting
  • A filter
  • The starting point Correct answer

Explanation: The anchor is the starting point.

3 Anchor and recursive parts: match the terms

Term Meaning
anchor base
recursive recursive
UNION ALL combine
step loop

All lessons in Advanced