How the Modulo Operator Works in MariaDB

In MariaDB, the modulo operator (%) returns the modulo operation. It returns the remainder of its first argument divided by its second argument.

Syntax

The syntax goes like this:

N % M

This returns the remainder of N divided by M.

The operation can also be done using the MOD keyword and the MOD() function. So you can use the following syntaxes to achieve the same outcome:

MOD(N,M)
N MOD M

Example

Here’s an example to demonstrate the modulo operator:

SELECT 9 % 2;

Result:

+-------+
| 9 % 2 |
+-------+
|     1 |
+-------+

Here are some more:

SELECT 
    8 % 2,
    134 % 27,
    9 % 5,
    9 % 10;

Result:

+-------+----------+-------+--------+
| 8 % 2 | 134 % 27 | 9 % 5 | 9 % 10 |
+-------+----------+-------+--------+
|     0 |       26 |     4 |      9 |
+-------+----------+-------+--------+

Compared with MOD & MOD()

Here’s an example that compares the syntaxes across the function and operators:

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

Result:

+-------+---------+-----------+
| 9 % 2 | 9 MOD 2 | MOD(9, 2) |
+-------+---------+-----------+
|     1 |       1 |         1 |
+-------+---------+-----------+

Non-Numeric Arguments

Here’s an example of what happens when we provide non-numeric arguments:

SELECT 'Bird' % 'Dog';

Result:

+----------------+
| 'Bird' % 'Dog' |
+----------------+
|           NULL |
+----------------+
1 row in set, 3 warnings (0.000 sec)

Let’s see the warning:

SHOW WARNINGS;

Result:

+---------+------+------------------------------------------+
| Level   | Code | Message                                  |
+---------+------+------------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: 'Bird' |
| Warning | 1292 | Truncated incorrect DOUBLE value: 'Dog'  |
| Warning | 1365 | Division by 0                            |
+---------+------+------------------------------------------+

Null Operands

The result is null if either operand is null:

SELECT 
    null % 2,
    134 % null,
    null % null;

Result:

+----------+------------+-------------+
| null % 2 | 134 % null | null % null |
+----------+------------+-------------+
|     NULL |       NULL |        NULL |
+----------+------------+-------------+