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
dividenddivided bydivisor. 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
MODwith division or integer division;MODonly 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
| Usage | Description |
|---|---|
| MOD(a, b) | Returns remainder of a divided by b |
| a % b | Alternative syntax for MOD function |
| Divisor cannot be zero | Division by zero causes error |
| Negative numbers | Remainder 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.