Why it happens: division by zero
SELECT 5 / 0 AS result;The engine may raise an error or return NULL. Either way, the mathematical problem is still there.
How to fix it in SQL
NULLIF(x, 0) returns NULL when x is zero. Dividing by NULL produces NULL avoids attempting an invalid division and makes it clear that the ratio cannot be calculated for that row.
WITH metrics(name, amount, units) AS (
VALUES ('A', 120.0, 4), ('B', 75.0, 0), ('C', 90.0, 3)
)
SELECT
name,
amount / NULLIF(units, 0) AS amount_per_unit
FROM metrics
ORDER BY name;| name | amount_per_unit |
|---|---|
| A | 30.0 |
| B | NULL |
| C | 30.0 |
How to check it
Test at least one positive divisor, one zero and one NULL, and check that each result makes sense.
How to avoid it next time
Do not replace an undefined result with zero without a rule that justifies it.
Related cases worth checking
What if you need to show zero?
You can wrap the expression in COALESCE(..., 0), but only if zero really is the right meaning. “A ratio cannot be calculated because there are no units” is not always the same as “the ratio is zero”.
COALESCE(amount / NULLIF(units, 0), 0)That pattern swaps an unknown, incalculable value for an explicit zero. Use it as a business decision, not as an automatic technical patch.
CASE also helps when you need to treat cases differently
If a zero divisor needs a label, a different rule or an alternative calculation, CASE makes the decision clearer:
CASE
WHEN units = 0 THEN NULL
ELSE amount / units
END AS amount_per_unitDo not swap a divisor of 0 for 1 just to avoid the error. That produces a different quotient and can lead to misleading metrics.
The behaviour depends on the engine
| Engine | Relevant behaviour |
|---|---|
| PostgreSQL | Division by zero corresponds to SQLSTATE error 22012 (division_by_zero). |
| SQL Server | With ANSI_WARNINGS ON, division by zero raises an error; settings can change that behaviour. |
| MySQL 8.4 | In a SELECT, division by zero returns NULL; SQL modes affect warnings and write operations. |
| SQLite | Documents that division by zero returns NULL. |
That is why it is a mistake to learn either “SQL always fails” or “SQL always returns NULL”. It is a difference between engines and settings, and you need to handle it deliberately.