Question presented to candidate: "Walk me through how a recursive CTE actually executes. What are the two parts, how does the database know when to stop, and what would you use one for?"
What a strong answer should cover:
- The shape:
WITH RECURSIVE name AS (anchor UNION [ALL] recursive term); the anchor runs once, the recursive term refers to the CTE itself - The execution model: a working table holds only the rows from the previous step; the recursive term runs against it, new rows are appended to the result and become the next working table; it stops when a step produces no rows
- Termination is the author's job: a WHERE condition, a join that runs out of children,
UNIONinstead ofUNION ALL, or a depth guard; engines differ on safety nets (SQL Server MAXRECURSION 100, MySQLcte_max_recursion_depth1000, none in PostgreSQL or SQLite) - Typical uses: walking trees and graphs (org charts, categories, bill of materials), generating series and calendars
- Restrictions: no aggregates in the recursive term, the CTE may be referenced only once there, column types must match (PostgreSQL rejects
varchar(20)vsvarchar) - Engine detail: PostgreSQL and MySQL require the
RECURSIVEkeyword, SQLite accepts plainWITH, SQL Server has noRECURSIVEkeyword at all
Code / implementation expected: Yes โ a number generator and a tree walk (descendants or ancestors) with a depth column.
Schema used by the examples: