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.
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.
A quick 3-question quiz on this lesson — instant feedback.
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.
Project-based Databases & SQL courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for Databases & SQL books — check the publication year so the examples match current versions.
Search Amazon →