SQLSTATE 22012 ERROR Class 22: Data Exception

division_by_zero division by zero — 22012

PostgreSQL error "division by zero" (SQLSTATE 22012): what it means, common causes, and how to fix it.

PG 12, 13, 14, 15, 16, 17, 18 Official docs
Last reviewed May 2025 Grounded in source

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

  1. Guard the divisor with NULLIF: revenue / NULLIF(quantity, 0) (yields NULL instead of erroring).
  2. Filter zero rows: WHERE quantity <> 0.
  3. Use a CASE expression to choose a fallback when the divisor is zero.
  4. 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”.

Was this helpful?