// math reference

SQL division by zero

What each engine does with x / 0: three of the five throw an error that aborts the query, two return NULL, so the same query can fail or silently empty a column.

類別
Math
Returns
error or NULL
In this category
57 of 82

語法

1 / 0
x / NULLIF(y, 0)  -- the portable guard

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

引擎支援

引擎Support備註
SQL Server 是 Msg 8134, Divide by zero error encountered. The statement fails; later statements in the batch still run unless XACT_ABORT is on or TRY/CATCH redirects
PostgreSQL 是 ERROR: division by zero; the whole statement fails
MySQL Different name or syntax SELECT returns NULL with a warning; with the default strict mode plus ERROR_FOR_DIVISION_BY_ZERO, INSERT and UPDATE fail instead
SQLite Different name or syntax Returns NULL: any x / 0 or x % 0 is NULL
Oracle 是 ORA-01476: divisor is equal to zero for NUMBER; BINARY_DOUBLE division returns Inf (1d / 0d)

範例

Any engine

SELECT 1 / NULLIF(0, 0) AS safe_div;  -- NULL, no error

PostgreSQL

SELECT revenue / NULLIF(days_active, 0) AS rev_per_day
FROM accounts;

MySQL

SELECT 1 / 0 AS div_by_zero;  -- NULL, plus a warning

小知識

  • The portable guard is NULLIF: x / NULLIF(y, 0) turns the fatal divisor into NULL, which then propagates as a NULL result instead of an error.
  • MySQL's NULL is a warning, not silence: SHOW WARNINGS reveals 'Division by 0'. MySQL 8's default sql_mode includes STRICT_TRANS_TABLES and ERROR_FOR_DIVISION_BY_ZERO, so INSERTs and UPDATEs that hit it fail.
  • Float division mostly follows the same rule: 1::float8 / 0 raises an error on PostgreSQL and 1e0 / 0 on SQL Server. Oracle is the exception: BINARY_DOUBLE 1d / 0d returns Inf.

Questions about 1 / 0

Does SQL return Infinity when dividing by zero?

Almost never. SQL Server, PostgreSQL and Oracle NUMBER raise an error; MySQL and SQLite return NULL. The one exception is Oracle BINARY_DOUBLE, where 1d / 0d returns Inf.

How do I avoid division-by-zero errors portably?

Wrap the divisor in NULLIF: x / NULLIF(y, 0). The zero becomes NULL, the result becomes NULL, and the query survives on every engine. Pair with COALESCE for a 0 default.

Why does my MySQL division return NULL silently?

In a SELECT, MySQL treats x / 0 as NULL with a warning, easy to miss in a big result set. The default strict mode with ERROR_FOR_DIVISION_BY_ZERO only turns it into an error for INSERT and UPDATE.

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.