// math reference

SQL REMAINDER function

Returns n1 - n2 * ROUND(n1/n2), the remainder after rounding the quotient: REMAINDER(8, 3) is -1 because 8/3 rounds to 3, while MOD(8, 3) is 2.

Kategorie
Math
Returns
numeric
In this category
56 of 82

Syntax

REMAINDER(n1, n2)

Engine-Unterstützung

EngineSupportNotizen
SQL Server Not built in No REMAINDER; % truncates the quotient instead
PostgreSQL Not built in No REMAINDER; % follows the dividend's sign
MySQL Not built in No REMAINDER; MOD follows the dividend's sign
SQLite Not built in No REMAINDER; % follows the dividend's sign
Oracle Ja REMAINDER(n1, n2) is built in; a zero divisor raises ORA-01476 for NUMBER and returns NaN for BINARY_DOUBLE

Beispiele

Oracle

SELECT REMAINDER(8, 3) AS rem, MOD(8, 3) AS mod_result FROM dual;  -- -1, 2

Oracle

SELECT REMAINDER(7, 3) AS rem FROM dual;  -- 1 (quotient 2.33 rounds to 2)

Gut zu wissen

  • Oracle's MOD truncates the quotient (n1 - n2 * TRUNC(n1/n2)); REMAINDER rounds it. They differ whenever the quotient's fractional part is above one half: MOD(8, 3) is 2, REMAINDER(8, 3) is -1.
  • The REMAINDER result can have either sign regardless of the inputs' signs, and always has magnitude at most half the divisor. MOD and % always take the dividend's sign.
  • Zero divisors flip: MOD(7, 0) returns 7, but REMAINDER(7, 0) raises ORA-01476 (and REMAINDER(7d, 0d) returns NaN).

Questions about REMAINDER

How is REMAINDER different from MOD in Oracle?

REMAINDER rounds the quotient to the nearest integer; MOD truncates it. REMAINDER(8, 3) is -1 while MOD(8, 3) is 2: the results differ by exactly one divisor whenever they differ.

Does any other engine have REMAINDER?

No. The other four have only truncating % or MOD, which keep the dividend's sign like C's fmod. Emulate with n1 - n2 * ROUND(n1 / n2), using a decimal division (n1 * 1.0 / n2) on engines where / truncates integers.

What does REMAINDER(7, 0) do?

Raises ORA-01476: divisor is equal to zero for NUMBER input, and returns NaN for BINARY_DOUBLE input. MOD(7, 0), by contrast, returns 7.

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