SQL MOD with a zero divisor
What a zero divisor does to a remainder: an error on two engines, NULL on two, and on Oracle MOD(7, 0) quietly returns 7.
- Categoria
- Math
- Returns
error or NULL- In this category
- 58 of 82
Sintaxe
MOD(x, 0)
x % 0
MOD(x, NULLIF(y, 0))
Each block is a separate form. The support table and the examples show which engine takes which.
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | % with 0 raises the divide-by-zero error |
| PostgreSQL | Sim | ERROR: division by zero |
| MySQL | Different name or syntax | MOD(x, 0) is NULL |
| SQLite | Different name or syntax | x % 0 is NULL; mod(x, 0) on 3.35+ likewise |
| Oracle | Different name or syntax | MOD(x, 0) returns x by definition; REMAINDER(x, 0) raises ORA-01476 |
Exemplos
PostgreSQL
SELECT 7 % NULLIF(0, 0) AS safe_mod; -- NULL
Oracle
SELECT MOD(7, 0) AS mod_zero FROM dual; -- 7
PostgreSQL
SELECT 7 % 0 AS mod_zero; -- ERROR: division by zero
MySQL
SELECT MOD(7, 0) AS mod_zero; -- NULL
Bom saber
- The NULLIF guard works identically for modulo: x % NULLIF(y, 0) degrades the error into a NULL.
- Oracle documents MOD(x, 0) = x, so a zero divisor passes the dividend straight through with no error. REMAINDER(x, 0) does raise ORA-01476.
- Zero-divisor checks matter in sharding: id % shard_count with an empty config produces an error, all-NULL keys, or on Oracle every id as its own shard.
Questions about MOD(x, 0)
What does MOD(x, 0) return?
Depends on the engine: MySQL and SQLite return NULL; SQL Server and PostgreSQL raise a division-by-zero error; Oracle returns x. Use NULLIF(y, 0) in the divisor for predictable NULLs.
Does the NULLIF trick work for modulo?
Yes: x % NULLIF(y, 0) returns NULL instead of erroring, exactly as it does for division. On Oracle write MOD(x, NULLIF(y, 0)), which also stops MOD from returning x.
Why did my sharding query return all NULLs?
The shard count was 0: on MySQL or SQLite, id % 0 silently yields NULL for every row, so nothing matches. Validate the divisor or use the error-raising engines to catch it.
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.