Compute n! using a recursive definition: 0! = 1, otherwise n! = n * (n - 1)!. The classic introduction to a self-referential function.

Algorithm

Canonical input n = 5 finishes after five reductions; the printed result is 120.

Basic Implementation

basic.sql
.mode list
.headers off
WITH RECURSIVE factorial(n, result) AS (
  SELECT 0, 1
  UNION ALL
  SELECT n + 1, result * (n + 1)
  FROM factorial
  WHERE n < 5
)
SELECT result FROM factorial WHERE n = 5;

Complexity

  • Time: O(n)
  • Space: O(n) for the materialized recursive CTE rows

Implementation notes

  • SQL: SQLite has no procedural RETURN value, so the recursive definition is unrolled in a WITH RECURSIVE factorial(n, result) CTE. The seed row (0, 1) is the base case; each recursive arm multiplies result by n + 1 and writes the next row. The WHERE n < 5 guard mirrors the imperative loop bound.
  • The final projection SELECT result FROM factorial WHERE n = 5 picks the row produced after the last multiplication. Replacing 5 with another input would reproduce n! for that value.
  • A direct SELECT exp(SUM(log(...))) would feel clever but lose the educational recursion the lesson is teaching; the explicit CTE keeps each multiplication step visible.
base case `0! = 1` ends the recursion.
recursive case `n! = n * (n - 1)!` reduces the input each step until the base case fires.