// math reference

SQL MOD function

Returns the remainder after division. It is used for sharding keys, every-nth-row sampling and cyclical buckets; the spelling, the sign rule and the divide-by-zero result all vary.

Category
Math
Returns
integer / numeric
In this category
5 of 82

Syntax

MOD(a, b)
a % b

Each block is a separate form. The support table and the examples show which engine takes which.

Engine support

EngineSupportNotes
SQL Server Different name or syntax % operator only, no MOD function
PostgreSQL Yes both MOD(a, b) and a % b
MySQL Yes MOD(a, b), a % b and a MOD b
SQLite Yes % operator; MOD(a, b) with the math functions (3.35+)
Oracle Yes MOD(a, b) only; % is not an operator

Examples

PostgreSQL

-- also MySQL, SQLite 3.35+ and Oracle
SELECT id, MOD(id, 4) AS shard FROM users;

SQL Server

SELECT id, id % 4 AS shard FROM users;

PostgreSQL

SELECT MOD(MOD(-7, 3) + 3, 3) AS positive_bucket;  -- 2

Good to know

  • The result takes the sign of the dividend: MOD(-7, 3) is -1 on every engine here, not 2. Use MOD(MOD(a, n) + n, n) for an always-positive bucket.
  • Dividing by zero differs: SQL Server and PostgreSQL raise an error, MySQL and SQLite return NULL, and Oracle's MOD(5, 0) returns 5.
  • SQL Server only has %, and Oracle only has MOD(). No single spelling works on both.

Questions about MOD / %

What is MOD(-7, 3)?

-1 on SQL Server, PostgreSQL, MySQL, SQLite and Oracle: the remainder follows the dividend's sign. Add the divisor back into a double MOD for an always-positive result.

Does SQL Server have a MOD function?

No, only the % operator: 7 % 3. PostgreSQL, MySQL and SQLite 3.35+ have both MOD() and %. Oracle has MOD() but no % operator.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.