The MOD() function is used to calculate the remainder of one number divided by another.
Syntax
MOD(x, y)
OR
x MOD y
OR
x % y
Definition and Usage
- The
MOD()function returns the remainder of dividingxbyy. - It is commonly used in mathematical calculations and logic involving divisors.
- Equivalent to the modulus operator (
%).
Parameter Values
| Parameter | Description |
|---|---|
x |
Required. The number to be divided. |
y |
Required. The divisor. |
Technical Details
- Introduced in: MySQL 4.0
- Return Value: The remainder of
x ÷ y.
Examples
Example 1: Simple remainder calculation
SELECT MOD(18, 4) AS Remainder;
Output:
Remainder
---------
2
Example 2: Using x MOD y syntax
SELECT 18 MOD 4 AS Remainder;
Output:
Remainder
---------
2
Example 3: Using % as an alternative
SELECT 18 % 4 AS Remainder;
Output:
Remainder
---------
2
Example 4: Remainder of a negative number
SELECT MOD(-18, 4) AS Remainder;
Output:
Remainder
---------
-2
Example 5: Remainder in a column
Find the remainder when dividing OrderQuantity by 5 in an Orders table:
SELECT OrderID, MOD(OrderQuantity, 5) AS Remainder FROM Orders;
Notes
- If
y = 0, the function returnsNULL(division by zero is undefined). - Use the
%operator as a shorthand forMOD()in queries.
Related Functions
DIV: Performs integer division and returns the integer quotient.FLOOR(): Returns the largest integer less than or equal to a given number.