BeginnerCoder

Lesson 21 — Recursive CTE

Recursive CTE: SQL that loops

A CTE (Common Table Expression) is a named temporary result written with WITH name AS (...). A recursive CTE refers to itself: an anchor part gives the first row(s), then a part after UNION ALL builds the next row from the previous one, until a WHERE stops it.

WITH RECURSIVE n(x) AS (
  SELECT 1                              -- anchor
  UNION ALL SELECT x + 1 FROM n WHERE x < 3   -- step
) SELECT x FROM n                       -- 1, 2, 3

Why it matters: recursive CTEs generate date ranges and walk hierarchies (org charts, folder trees) directly in the database.

Want it another way?
Task

Fill in the recursive step so each row doubles the previous value while it is below 100. Expected: 1 2 4 8 16 32 64 128.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Databases & SQL

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.