// math reference

SQL MOD sign of the result

Covers the sign of the modulo result: every engine truncates the quotient, so -7 % 3 is -1, not the 2 that Python, Ruby or a floored modulo would give.

Category
Math
Returns
numeric
In this category
80 of 82

Syntax

MOD(-7, 3)
-7 % 3

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

Engine support

EngineSupportNotes
SQL Server Yes -7 % 3 is -1: sign of the dividend
PostgreSQL Yes -7 % 3 is -1: sign of the dividend
MySQL Yes MOD(-7, 3) is -1: sign of the dividend
SQLite Yes -7 % 3 is -1: sign of the dividend
Oracle Yes MOD(-7, 3) is -1; Oracle's documentation contrasts MOD with the floored 'classical modulus' n2 - n1 * FLOOR(n2/n1)

Examples

Oracle

SELECT MOD(-7, 3) AS oracle_mod FROM dual;  -- -1

MySQL

SELECT MOD(-7, 3) AS mysql_mod;  -- -1

PostgreSQL

SELECT ((-7) % 3 + 3) % 3 AS floored;  -- 2; on Oracle write MOD(MOD(-7, 3) + 3, 3)

Good to know

  • It matters for bucketing: id % 4 on a negative id gives -1, -2 or -3, so a CASE over 0..3 misses those rows. ((x % n) + n) % n maps every result into 0..n-1.
  • Ports from Python or Ruby break here: their -7 % 3 is 2. All five SQL engines follow C's truncating rule instead, and none offers a floored variant.
  • Oracle's REMAINDER is the odd one: it rounds the quotient, so REMAINDER(-7, 3) is -1 but REMAINDER(-8, 3) is 1, a different sign from MOD(-8, 3) = -2.

Questions about MOD sign

What is MOD(-7, 3) in SQL?

-1 on all five engines: SQL Server, PostgreSQL, MySQL, SQLite and Oracle all take the sign of the dividend. Python and Ruby return 2, which is the usual source of confusion.

How do I get a positive modulo everywhere?

Use the double-mod trick: ((x % n) + n) % n maps any result into 0..n-1 for positive n. On Oracle, which has no %, write MOD(MOD(x, n) + n, n).

Does Oracle's MOD use floor semantics?

No. Oracle's documentation says MOD differs from the floored classical modulus, n2 - n1 * FLOOR(n2/n1), whenever the operands have opposite signs, so MOD(-7, 3) is -1 as on the other engines. Oracle's MOD(x, 0) returning x is its real quirk.

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// 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.