Recursive CTE Factorial

Generate factorial numbers using a SQL recursive common table expression with a termination condition.

SqlData Integrity

Code

sqlsnippet
8 lines
WITH RECURSIVE factorial(n, result) AS (
  SELECT 0, 1
  UNION ALL
  SELECT n + 1, result * (n + 1)
  FROM factorial
  WHERE n < 12
)
SELECT n, result FROM factorial;

What the code does

What runs is SELECT, with factorial as the object involved.

Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause narrowing which rows one statement affects; a UNION combining result sets from separate queries.

Applying it

The factorial table is the working surface here.

Statements that matter

WITH RECURSIVE factorial(n, result) AS (
  SELECT 0, 1
  UNION ALL
  SELECT n + 1, result * (n + 1)
  FROM factorial
  WHERE n < 12
)
SELECT n, result FROM factorial;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
The references are `factorial`.