In PostgreSQL, mod()
is a mathematical function that returns the remainder from division of the first argument (the dividend) by the second argument (the divisor).
Syntax
The syntax goes like this:
mod(y, x)
The function returns the remainder of y
/x
.
Example
Here’s an example to demonstrate how it works.
SELECT mod(5, 2);
Result:
1
In this case, 5 divided by 2 has a quotient of 2 and a remainder of 1, so the result is 1.
Negative Arguments
Here’s an example with negative arguments.
SELECT
mod(-5, 2),
mod(5, -2),
mod(-5, -2);
Result:
mod | mod | mod -----+-----+----- -1 | 1 | -1
Zero Dividend
Here’s an example with a dividend of zero.
SELECT mod(0, 2);
Result:
0
Division by Zero
Now let’s swap it around and make the divisor zero.
SELECT mod(2, 0);
Result:
ERROR: division by zero