In PostgreSQL, factorial()
is a mathematical function that returns the factorial of a given integer. We pass the integer (it accepts bigint
), and it returns the factorial as a numeric value.
In mathematics, the factorial is the product of all positive integers less than or equal to a given positive integer. It’s denoted by that integer and an exclamation point.
Example
Here’s an example to demonstrate:
SELECT factorial(4);
Result:
24
Here’s how it arrives at that result:
4! = 4 × 3 × 2 × 1 = 24
So to get the factorial, we multiply all whole numbers from our chosen number down to 1.
As you can imagine, this has the potential to produce some large numbers. Here’s another example:
SELECT factorial(150);
Result:
57133839564458545904789328652610540031895535786011264182548375833179829124845398393126574488675311145377107878746854204162666250198684504466355949195922066574942592095735778929325357290444962472405416790722118445437122269675520000000000000000000000000000000000000
Passing a Negative Value
Passing a negative value results in an error:
SELECT factorial(-4);
Result:
ERROR: factorial of a negative number is undefined
However, in PostgreSQL 13 and earlier the function erroneously returns 1
.
Passing a Null Value
Passing a null value results in null
being returned:
SELECT factorial(null);
Result:
null
Passing the Wrong Argument Type
If the argument is not an integer, an error is returned:
SELECT factorial('cat');
Result:
ERROR: invalid input syntax for type bigint: "cat"
LINE 1: SELECT factorial('cat');
^
About Factorial
The Math is Fun website has a nice, simple explanation about how the factorial function works in mathematics, along with examples.