division by zero
SQLSTATE 22012 is raised when an arithmetic expression attempts to divide a number by zero, or when a modulo operation has a zero divisor. The statement is aborted.
- 1Dividing a numeric, integer, or floating-point value by zero in SQL or PL/pgSQL
- 2Using modulo (%) with a zero divisor
- 3A divisor column or expression evaluates to zero for some rows in a query
Dividing a column value by another column that contains zero.
SELECT revenue / expenses FROM departments; -- fails when expenses = 0
expected output
ERROR: division by zero
Fix 1
Use NULLIF to prevent zero division
WHEN When the divisor may be zero and NULL is an acceptable result.
SELECT revenue / NULLIF(expenses, 0) FROM departments;
Why this works
NULLIF(expenses, 0) returns NULL when expenses is 0. Division by NULL produces NULL rather than an error.
Fix 2
Use CASE to return a default value
WHEN When a specific default (e.g., 0 or 100) should replace the division result.
SELECT CASE WHEN expenses = 0 THEN 0 ELSE revenue / expenses END FROM departments;
Why this works
The CASE avoids evaluating the division branch when the divisor is zero.
✕ Filter out zero-divisor rows without understanding why they exist
Zero expenses may indicate data quality issues that should be investigated and fixed at the source.
Class 22 — Data Exception
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev