Recursive CTE - Factorial
Recursive CTE - Factorial is a SQL statement in the CTE (WITH) category. Recursive CTE computing mathematical sequences like factorial numbers. The syntax is WITH RECURSIVE factorial(n, fact) AS (VALUES (1, 1) UNION ALL SELECT n+1, fact*(n+1) FROM factorial WHERE n < 10) SELECT * FROM factorial;. It returns factorial sequence. A typical example: WITH RECURSIVE factorial(n, fact) AS ( VALUES (1, 1) UNION ALL SELECT n + 1, fact * (n + 1) FROM factorial WHERE n < 10 ) SELECT n AS number, fact AS factorial_value FROM factorial; -- 1, 1 -- 2, 2 -- 3, 6 -- 4, 24 -- 5, 120 -- 6, 720 -- 7, 5040 -- 8, 40320 -- 9, 362880 -- 10, 3628800 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).