3 Ways to Return the Modulo in MariaDB

The modulo operation returns the remainder or signed remainder of a division, after one number is divided by another.

If you need to get the modulo of a number in MariaDB, here are three options.

The MOD() Function

The MOD() function is specifically designed to return the modulo operation. It accepts two arguments. It returns the remainder of its first argument divided by its second argument.

Example:

SELECT MOD(47, 3);

Result:

+------------+
| MOD(47, 3) |
+------------+
|          2 |
+------------+

The Modulo Operator

The modulo operator (%) does the same thing, except that you use a different syntax:

SELECT 47 % 3;

Result:

+--------+
| 47 % 3 |
+--------+
|      2 |
+--------+

The MOD Keyword/Operator

Although this option is listed in the MariaDB documentation for the MOD() function, its syntax is more inline with the modulo operator.

Basically, you just replace % with MOD and it works exactly the same:

SELECT 47 MOD 3;

Result:

+----------+
| 47 MOD 3 |
+----------+
|        2 |
+----------+

Null Arguments

All three options return null if either argument/operand is null.

Example:

SELECT 
    MOD(null, 2),
    null % 2,
    null MOD 2;

Result:

+--------------+----------+------------+
| MOD(null, 2) | null % 2 | null MOD 2 |
+--------------+----------+------------+
|         NULL |     NULL |       NULL |
+--------------+----------+------------+