MOD
The MOD
(modulo) operation in SQL returns the remainder of the division of one number by another. It is represented by the MOD
keyword or the %
(percent) symbol. The MOD
operation can be useful in various scenarios, such as calculating cyclic values or determining if one number is evenly divisible by another.
Basic syntax
-- Using MOD keyword
SELECT MOD(column1, column2) AS result
FROM your_table;
-- Using % symbol
SELECT column1 % column2 AS result
FROM your_table;
Example
SELECT 10 MOD 3 AS modulo_result;
-- Output: 1
SELECT 15 % 4 AS modulo_result;
-- Output: 3
SELECT column1, column2, column1 % column2 AS modulo_result
FROM your_table;
Handling division by zero
Just like with division, it's important to handle cases where the divisor is zero to avoid errors. You can use a CASE
statement or NULLIF
function for this purpose.
Example
SELECT column1, column2,
CASE WHEN column2 <> 0 THEN column1 % column2 ELSE NULL END AS safe_modulo_result
FROM your_table;