Return the factorial of a non-negative integer.
FACTORIAL(n)
## Overview Returns the factorial of a non-negative integer, defined as n! = n * (n - 1) * ... * 1 with 0! = 1 by convention. FACTORIAL is a closed-form helper for combinatorial calculations in SQL: counting permutations, computing binomial coefficients, and constructing factorial-moment estimators. Because factorials grow extremely fast (21! already exceeds 2^63 - 1), FACTORIAL is defined only up to n = 20. For larger inputs, compute log-factorials via LGAMMA or use arbitrary-precision arithmetic outside SQL. ## Behavior - Accepts a non-negative integer in [0, 20]. - Returns a BIGINT. - Returns NULL if the argument is NULL. - Raises an error for negative inputs and for inputs above 20 (overflow). - FACTORIAL(0) = 1 by convention. ## Numeric precision - All results in the supported range are exactly representable in BIGINT; FACTORIAL is exact. - For inputs above 20, consider computing ln(n!) = LGAMMA(n + 1) and working in log-space. ## Compatibility - Matches the PostgreSQL FACTORIAL scalar function. - The cap at n = 20 reflects the BIGINT representation ceiling shared by most SQL engines that expose a direct factorial function.
| Name | Type | Description |
|---|---|---|
n | Specifies a non-negative integer. Must be in the range 0 to 20 inclusive; values outside this range produce an overflow error because 21! exceeds the BIGINT maximum. |
-- Factorial of 0 is 1 by convention
SELECT FACTORIAL(0); -- 1
-- Basic literal
SELECT FACTORIAL(5); -- 120
-- Factorial of 10
SELECT FACTORIAL(10); -- 3628800
-- Factorial of 1
SELECT FACTORIAL(1); -- 1
-- Maximum supported value (20! is the largest that fits in BIGINT)
SELECT FACTORIAL(20); -- 2432902008176640000
-- NULL propagation
SELECT FACTORIAL(NULL); -- NULL