// math reference

SQL factorial

Computes n!, the product of 1 through n: factorial(5) is 120 on PostgreSQL, and a recursive CTE builds the same product on the other engines.

Категория
Math
Returns
integer / numeric
In this category
28 of 82

Синтаксис

factorial(n)  -- PostgreSQL
recursive CTE elsewhere

Each block is a separate form. The support table and the examples show which engine takes which.

Поддержка движка

ДвижокSupportЗаметки
SQL Server Not built in No built-in; use a recursive CTE
PostgreSQL Да factorial(bigint) returns numeric; the postfix 5! and prefix !!5 operators were removed in PostgreSQL 14
MySQL Not built in No built-in; recursive CTE on 8.0+
SQLite Not built in No built-in; recursive CTE on 3.8.3+
Oracle Not built in No built-in; recursive subquery factoring

Примеры

PostgreSQL

SELECT factorial(5) AS f5, factorial(20) AS f20;  -- 120, 2432902008176640000

SQLite

WITH RECURSIVE f(n, fact) AS (
  SELECT 1, 1
  UNION ALL
  SELECT n + 1, fact * (n + 1) FROM f WHERE n < 20
)
SELECT fact FROM f WHERE n = 20;  -- 2432902008176640000

Полезно знать

  • Factorials explode: 21! already exceeds a 64-bit integer. PostgreSQL's factorial() returns numeric, so it stays exact; a hand-rolled CTE on BIGINT overflows at 21.
  • The portable pattern is a recursive CTE multiplying a running product, capped with an explicit n to avoid runaway recursion.
  • For combinatorics in bulk, LN-based sums are safer: summing LN(1)..LN(n) avoids overflow, then EXP the total.

Questions about FACTORIAL

Does SQL have a FACTORIAL function?

PostgreSQL does: factorial(5) is 120. It dropped the 5! and !!5 operator forms in version 14, so old queries using them need rewriting. SQL Server, MySQL, SQLite and Oracle have nothing built in; use a recursive CTE with a running product.

How large can a factorial be in SQL?

20! fits in a 64-bit integer (about 2.4e18); 21! does not. PostgreSQL's factorial() returns numeric and handles far larger n; elsewhere switch the CTE to DECIMAL/NUMBER or sum logarithms.

Is a recursive factorial slow?

For small n it is a handful of rows and fine. For per-row combinatorics over big tables, precompute the values or use the log-sum approach instead of recursing per row.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.