The MOD() function in SQL is a mathematical function used to return the remainder after dividing one number by another.
- Useful for checking whether a number is even or odd.
- Used to perform calculations based on repeating or cyclical values.
Syntax
MOD(number1, number2)- number1: The number to be divided.
- number2: The number by which n
umber1is divided.
Note: The MOD() function is supported by MySQL, Oracle and PostgreSQL. In SQL Server, the % operator is used instead of MOD(). SQLite also supports the % operator for finding the remainder.
Working
Below are some examples of the MOD() function to understand how it is used with numeric values.
Example 1: Find the Remainder
In this example, we will find the remainder when 17 is divided by 5.
Query:
SELECT MOD(17, 5) AS remainder;Output:
Example 2: Check Whether a Number is Even or Odd
In this example, we will use MOD() to check whether a number is even or odd.
Query:
SELECT MOD(10, 2) AS remainder;Output:
- A remainder of 0 means the number is evenly divisible by 2.
- Therefore, 10 is an even number.
Example 3: Use MOD() on a Table Column
Let us create a order table containing order_id .
Now, we can use the MOD() function to check the remainder of each order_id when divided by 2.
Query:
SELECT order_id,
quantity,
MOD(quantity, 5) AS remainder
FROM orders;
Output:
- Returns the remainder after dividing each quantity by 5.
- A remainder of 0 indicates that the quantity is evenly divisible by 5.
- A non-zero remainder indicates that the quantity is not evenly divisible by 5.