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.
- Категория
- Math
- Returns
integer / numeric- In this category
- 5 of 82
Синтаксис
MOD(a, b)
a % b
Each block is a separate form. The support table and the examples show which engine takes which.
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Different name or syntax | % operator only, no MOD function |
| PostgreSQL | Да | both MOD(a, b) and a % b |
| MySQL | Да | MOD(a, b), a % b and a MOD b |
| SQLite | Да | % operator; MOD(a, b) with the math functions (3.35+) |
| Oracle | Да | MOD(a, b) only; % is not an operator |
Примеры
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
Полезно знать
- 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.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.