SQLSTATE 22012 ERROR Class 22: Data Exception

division_by_zero Division By Zero — SQLSTATE 22012

A division or modulo operation had a zero divisor.

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

Symptoms

A division or modulo operation had a zero divisor.

  • The error is written to the server log and returned to the client carrying SQLSTATE 22012.
  • Any driver (libpq, JDBC, psycopg, npgsql, pgx) surfaces this code in its error object so you can branch on it programmatically.
  • PL/pgSQL can trap it by name: EXCEPTION WHEN division_by_zero THEN.

Environment

Severity: ERROR  |  PostgreSQL versions: 12, 13, 14, 15, 16, 17

Reproduce with the exact statement and read the full message in the server log (raise log_min_messages / set log_min_error_statement for more context).

Root Cause

SQL evaluated x / 0 or x % 0.

Common causes:

  • A denominator column or expression evaluating to zero.
  • Aggregates producing a zero divisor.
  • Computed ratios over empty groups.

Diagnostic Queries

Recovery

Steps to resolve 22012:

  1. Guard the divisor with x / NULLIF(divisor, 0) — it yields NULL instead of erroring.
  2. Use CASE WHEN divisor = 0 THEN ... ELSE x/divisor END.
  3. Filter out zero-divisor rows before the calculation.

Reference: PostgreSQL error codes — Class 22 (Data Exception).

Was this helpful?