100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
SQL Mastery
35 minbeginner

Recursive CTEs

Some data is hierarchical or chained: an org chart of managers, a tournament bracket, a sequence of dates, a tree of categories. Ordinary queries cannot traverse an unknown number of levels, because you would need to know in advance how many joins to write. A recursive CTE solves this by repeatedly applying a query to its own growing result until no new rows appear.

A recursive CTE has a distinctive three-part shape: an anchor member that produces the starting rows, a recursive member that derives new rows from the previous iteration, and a UNION that combines them. The engine runs the recursive member again and again, each time feeding the previous output back in, until an iteration adds nothing further, at which point the recursion stops.

Recursive CTEs are the standard SQL tool for hierarchies and generated sequences, problems that are awkward or impossible to express otherwise. They require care, because a missing termination condition causes infinite recursion, but once understood they elegantly handle org charts, bill-of-materials trees, captaincy chains, and gap-free date series within a single, self-contained query.

Analogy🏏Cricket
🏏 Think of it like cricket: Imagine the end of an IPL innings when the scorer announces the team's final total. Just as the scorer does not read out all one hundred and twenty individual deliveries but instead sums them into a single team score, SUM folds many row values into one number. Just as the commentator reports the highest individual score, the average partnership, and the number of wickets, MAX, AVG, and COUNT each summarise the innings differently. Just as a not-out batsman with no deliveries faced does not lower the team average, aggregates skip NULLs when computing. Just as the announcement is one figure no matter whether the innings had fifty deliveries or two hundred and fifty, an aggregate collapses any number of rows into a single result. This reveals why summaries answer the questions about the whole that individual deliveries cannot.
Lesson 22 of 35
0% complete