Lesson

MySQL MOD() Function

10 min reading
Free Course

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 SELECT queries, MOD(10, 0) returns NULL in default modes. In strict SQL modes with ERROR_FOR_DIVISION_BY_ZERO, using MOD(n, 0) during INSERT or UPDATE raises an error. Wrap variable divisors with NULLIF(m, 0).
  • Sign of negative remainders: MySQL keeps the sign of the dividend n, NOT the divisor m. For instance, MOD(-10, 3) returns -1, while MOD(10, -3) returns 1.
  • Decimal inputs work too: Unlike C or Java's % operator on integers only, MySQL MOD(5.75, 2) works on decimals and returns 1.75.
  • NULL propagation: If either n or m is NULL, MOD() returns NULL.

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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum