0
0
MysqlHow-ToBeginner · 3 min read

How to Use MOD Operator in MySQL: Syntax and Examples

In MySQL, the MOD function returns the remainder of a division between two numbers. You use it as MOD(dividend, divisor) or with the modulo operator % like dividend % divisor.
📐

Syntax

The MOD function in MySQL calculates the remainder when one number is divided by another.

  • MOD(dividend, divisor): Returns the remainder of dividend divided by divisor.
  • dividend % divisor: An alternative operator syntax that does the same.
sql
MOD(dividend, divisor)
dividend % divisor
💻

Example

This example shows how to use MOD and % to find remainders of division in a query.

sql
SELECT MOD(10, 3) AS mod_function_result, 10 % 3 AS mod_operator_result;
Output
+---------------------+---------------------+ | mod_function_result | mod_operator_result | +---------------------+---------------------+ | 1 | 1 | +---------------------+---------------------+
⚠️

Common Pitfalls

Common mistakes when using MOD include:

  • Dividing by zero causes an error. Always ensure the divisor is not zero.
  • Using negative numbers can produce negative remainders, which might be unexpected.
  • Confusing MOD with division or integer division; MOD only returns the remainder.
sql
/* Wrong: divisor is zero - causes error */
SELECT MOD(10, 0);

/* Right: check divisor before using MOD */
SELECT CASE WHEN 0 = 0 THEN NULL ELSE MOD(10, 0) END AS safe_mod;
📊

Quick Reference

UsageDescription
MOD(a, b)Returns remainder of a divided by b
a % bAlternative syntax for MOD function
Divisor cannot be zeroDivision by zero causes error
Negative numbersRemainder sign follows dividend sign

Key Takeaways

Use MOD(a, b) or a % b to get the remainder of division in MySQL.
Never use zero as the divisor to avoid errors.
MOD returns the remainder, not the quotient or integer division result.
Negative dividends produce negative remainders in MOD.
Both MOD function and % operator work the same way.