MOD() in SQL
Returns the remainder after dividing one number by another. Also available as % operator in many databases.
Syntax
Return type
MOD() Function Example
What is MOD() in SQL?
The MOD()
function in SQL returns the remainder after dividing one number by another. It is commonly used for checking divisibility, cyclic operations, and mathematical computations. Many databases also support the %
operator as an alternative to MOD()
, though syntax may vary. This function is available in MySQL, PostgreSQL, SQL Server, and Oracle. If the divisor is zero, the function may return an error or NULL, depending on the database system. MOD()
is useful in scenarios such as identifying even/odd numbers, distributing records into groups, and implementing circular indexing.
Parameters:
dividend: The number to be divided
divisor: The number to divide by
Example Use Cases:
-- Check for even/odd numbers
-- Rotate through values (like days of week)
-- Distribute items into groups
Notes:
Behavior: Returns NULL if divisor is 0
Performance Considerations: Basic arithmetic operation, efficient
Version Info: Core mathematical function available in all major DBMS
Deprecated/Recommended Alternatives: % operator often preferred
Error Handling:
Error: Returns NULL if either input is NULL or if divisor is 0
Recommendation: Use NULLIF to handle zero divisor cases
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
MOD() or %
MOD(17, 5)
Returns NULL
PostgreSQL
MOD() or %
MOD(17, 5)
Returns NULL
SQL Server
% operator
17 % 5
Returns NULL
SQLite
% operator
17 % 5
Returns NULL
BigQuery
MOD()
MOD(17, 5)
Returns NULL
Snowflake
MOD() or %
MOD(17, 5)
Returns NULL
Athena
MOD()
MOD(17, 5)
Returns NULL
Related Functions:
FLOOR()
Rounds a number down to the nearest integer or to a specified decimal place. Always rounds toward negative infinity.
CEIL()/CEILING()
Rounds a number up to the nearest integer or to a specified decimal place. Always rounds away from zero for positive numbers and toward zero for negative numbers.
ROUND()
Rounds a number to a specified number of decimal places or to the nearest integer.