Diagnostic Queries
Symptoms
An arithmetic expression divided by zero — with /, the modulo operator %, or a function such as div(). SQL has no defined result for division by zero, so PostgreSQL raises an error instead of returning a value.
- The statement aborts with SQLSTATE 22012.
- Typically one or more rows have a zero divisor.
- Often surfaces when computing ratios or percentages over real data.
What the server log shows
ERROR: division by zero
STATEMENT: SELECT revenue / quantity FROM sales;
Why PostgreSQL raises this — what the manual says
As Section 9.3 Mathematical Functions and Operators explains:
Division by zero is mathematically undefined, so the division (/) and modulo (%) operators raise a division-by-zero error rather than returning a value when the divisor is zero.
When the divisor of / or % evaluates to zero (integer, numeric, or floating types alike) the operator raises 22012 and the statement aborts. The usual trigger is a per-row divisor column that contains a zero for some rows.
Common causes
- A divisor column or expression that is zero for some rows.
- Computing a ratio/percentage before filtering out zero denominators.
- An aggregate denominator that turns out to be zero.
How to fix it
- Guard the divisor with
NULLIF:revenue / NULLIF(quantity, 0)(yieldsNULLinstead of erroring). - Filter zero rows:
WHERE quantity <> 0. - Use a
CASEexpression to choose a fallback when the divisor is zero. - Validate inputs so denominators are never zero.
Diagnostic query
-- Find the rows that would divide by zero
SELECT * FROM sales WHERE quantity = 0;
These rows are the ones triggering the error.
Related & next steps
Reference: PostgreSQL 18 Section 9.3 “Mathematical Functions and Operators”.
Thanks — noted. This helps keep the database accurate.