MySQL numeric functions
MySQL string functions
MySQL Date/Time functions
MySQL aggregate functions
MySQL flow control functions
The MOD()
function in MySQL is a mathematical function that returns the remainder of a division operation. In other words, it calculates the modulus of two numbers.
Syntax:
MOD(number, divisor)
Here, number
is the number for which to find the modulus, and divisor
is the number by which to divide the number.
Alternatively, you can use the %
operator to perform the modulus operation:
number % divisor
Examples:
1. Using MOD()
Function:
Let's say you want to find the remainder of the division of 10 by 3. You would write:
SELECT MOD(10, 3);
This will return 1
, because when 10 is divided by 3, the quotient is 3 and the remainder is 1.
2. Using %
Operator:
The same operation can be performed using the %
operator:
SELECT 10 % 3;
This will also return 1
.
Usage in a Table:
Consider the following orders
table:
OrderID | CustomerID | Quantity |
---|---|---|
1 | 101 | 5 |
2 | 102 | 12 |
3 | 103 | 7 |
4 | 104 | 15 |
5 | 105 | 9 |
If you want to select all orders where the Quantity
is odd, you can use the MOD()
function to check the remainder of the division of the Quantity
by 2:
SELECT * FROM orders WHERE MOD(Quantity, 2) = 1;
This will return all rows where Quantity
is an odd number:
OrderID | CustomerID | Quantity |
---|---|---|
1 | 101 | 5 |
3 | 103 | 7 |
4 | 104 | 15 |
5 | 105 | 9 |
Remember that the MOD()
function can only be used with numeric data types. If it's used with non-numeric data types, MySQL will attempt to convert the data to numbers before performing the operation.
MySQL MOD Function Example:
SELECT MOD(dividend, divisor) AS remainder FROM table_name;
How to Use MOD Function in MySQL:
SELECT MOD(15, 4) AS remainder;
Finding the Remainder with MOD in MySQL:
SELECT MOD(27, 5) AS remainder;
Using MOD for Modulo Arithmetic in MySQL:
SELECT number, MOD(number, 2) AS is_even FROM numbers_table;
MOD Function with WHERE Clause in MySQL:
SELECT order_id, total_amount FROM orders WHERE MOD(order_id, 2) = 0; -- Select orders with even order_id
Handling Negative Numbers with MOD in MySQL:
SELECT MOD(-8, 3) AS negative_remainder;
Examples of Using MOD Function in MySQL Queries:
SELECT product_id, stock_quantity FROM products WHERE MOD(stock_quantity, 5) = 0; -- Select products with stock quantity divisible by 5
SELECT employee_id, salary FROM employees WHERE MOD(employee_id, 2) = 1; -- Select employees with odd employee_id
Applying MOD to Date and Time Values in MySQL:
SELECT order_id, order_date FROM orders WHERE MOD(MONTH(order_date), 2) = 0; -- Select orders with even month