MySQL MOD() Function
MySQL MOD() Function: Calculating Division Remainders
The MOD() function returns the remainder after dividing one number (n) by another (m). In MySQL, MOD(n, m), n % m, and n MOD m all execute the exact same modulo operation.
Modulo arithmetic helps you identify even or odd IDs (id % 2 = 0), distribute work across shard buckets (user_id % 4), check whether a quantity fills whole packs cleanly, or wrap cyclic counters.
Syntax
MOD(n, m)
n % m
n MOD m
n: Dividend (integer or decimal).m: Divisor (integer or decimal).
Practical Example
Suppose demo_orders holds bulk warehouse orders packed in boxes of 6 units. You want to find orders that have leftover loose units (MOD(quantity, 6) <> 0) so packers can stage partial boxes separately.
SELECT
order_id,
quantity,
quantity DIV 6 AS full_boxes,
MOD(quantity, 6) AS leftover_units
FROM demo_orders
WHERE MOD(quantity, 6) <> 0
ORDER BY order_id;
| order_id | quantity | full_boxes | leftover_units |
|---|---|---|---|
| 510 | 14 | 2 | 2 |
| 512 | 25 | 4 | 1 |
| 515 | 5 | 0 | 5 |
Every returned row has a non-zero remainder after dividing quantity by 6. Orders with exact multiples like 12 or 18 yield 0 and are excluded.
Common Mistakes & NULL Behavior
- Dividing by zero with MOD(n, 0): In
SELECTqueries,MOD(10, 0)returnsNULLin default modes. In strict SQL modes withERROR_FOR_DIVISION_BY_ZERO, usingMOD(n, 0)duringINSERTorUPDATEraises an error. Wrap variable divisors withNULLIF(m, 0). - Sign of negative remainders: MySQL keeps the sign of the dividend
n, NOT the divisorm. For instance,MOD(-10, 3)returns-1, whileMOD(10, -3)returns1. - Decimal inputs work too: Unlike C or Java's
%operator on integers only, MySQLMOD(5.75, 2)works on decimals and returns1.75. - NULL propagation: If either
normisNULL,MOD()returnsNULL.
Frequently Asked Questions
Is there any difference between MOD(n, m) and n % m in MySQL?
No. Both are identical in behavior and performance. MOD(n, m) follows standard SQL, while % is compact for inline expressions.
How do I keep remainders positive even when n is negative?
Compute MOD(MOD(n, m) + m, m) when m > 0, which turns -10 mod 3 into 2 instead of -1.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.