Recursive CTE - Fibonacci Series
Recursive CTE - Fibonacci Series is a SQL statement in the CTE (WITH) category. Recursive CTE generating mathematical sequences like Fibonacci. Shows the power of recursive computation. The syntax is WITH RECURSIVE fib(n, a, b) AS (VALUES (1, 0, 1) UNION ALL SELECT n+1, b, a+b FROM fib WHERE n < 10) SELECT .... It returns generated number sequence. A typical example: WITH RECURSIVE fibonacci(n, a, b) AS ( VALUES (1, 0, 1) UNION ALL SELECT n + 1, b, a + b FROM fibonacci WHERE n < 15 ) SELECT n AS position, a AS fib_number FROM fibonacci; -- Generates: 1:0, 2:1, 3:1, 4:2, 5:3, 6:5, 7:8, 8:13, 9:21, 10:34, 11:55, 12:89, 13:144, 14:233, 15:377 A close relative is WITH (CTE), which common Table Expression — define a named temporary result set that can be referenced in the main query. A close relative is Recursive CTE, which a CTE that references itself, allowing hierarchical or recursive queries (org charts, tree structures).