SQL error · GROUP BY and calculations

Division by zero

Problem: The divisor is zero; the engine may reject the division or return NULL.

Solution: Use NULLIF(divisor, 0) and decide what that missing result should mean.

Why it happens: division by zero

Zero divisor
SELECT 5 / 0 AS result;

The engine may raise an error or return NULL. Either way, the mathematical problem is still there.

“Division by zero” error messages by engine

The exact wording depends on the database. Compare these common messages with the one in your console.

EngineTypical message
PostgreSQLERROR: division by zero
MySQLDevuelve NULL en un SELECT; en mode strict, INSERT y UPDATE fallan with ERROR 1365 (22012): Division by 0
SQL ServerMsg 8134, Level 16: Divide by zero error encountered.
OracleORA-01476: divisor is equal to zero
SQLiteDevuelve NULL without error

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.

Protecting the divisor
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;
Result verified in SQLite 3.46.1
nameamount_per_unit
A30.0
BNULL
C30.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_unit

Do 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

EngineRelevant behaviour
PostgreSQLDivision by zero corresponds to SQLSTATE error 22012 (division_by_zero).
SQL ServerWith ANSI_WARNINGS ON, division by zero raises an error; settings can change that behaviour.
MySQL 8.4In a SELECT, division by zero returns NULL; SQL modes affect warnings and write operations.
SQLiteDocuments 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.