Recursive CTE Factorial
Generate factorial numbers using a SQL recursive common table expression with a termination condition.
Code
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables or CTEs does it reference?
- The references are `factorial`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.