PostgreSQL Error 22012: Division by Zero

PostgreSQL error 22012 (Division by Zero) explained: what it means, why it happens, and how to fix it — with copy-paste code examples.

SQLSTATE 22012 PostgreSQL Last verified 2026-08-19

Quick Answer

Use NULLIF(divisor, 0) so the division yields NULL instead of error. If that does not apply, wrap with CASE WHEN divisor = 0 THEN NULL ... for explicit control — the full checklist is below.

Error Code

SQLSTATE: 22012
Official name: Division by Zero
Service: PostgreSQL

What does this error mean?

Division by zero was attempted.

Common Causes

How to Fix

  1. Use NULLIF(divisor, 0) so the division yields NULL instead of error
  2. Wrap with CASE WHEN divisor = 0 THEN NULL ... for explicit control
  3. Validate divisors at the application layer before composing SQL

Code Examples

Safe division with NULLIF sql
SELECT a / NULLIF(b, 0) AS ratio FROM metrics;

NULLIF returns NULL when b is 0, making the division return NULL instead of raising 22012.

Framework-Specific Fixes

sqlalchemy

Use nullif() in the expression to short-circuit zero divisors.

from sqlalchemy import func, nullif
expr = col_a / nullif(col_b, 0)
supabase

Create a view or RPC that applies NULLIF so clients never send raw a/b.

CREATE VIEW ratios AS
  SELECT id, a / NULLIF(b, 0) AS ratio FROM t;

You Might Also Like

Frequently Asked Questions

Why am I seeing PostgreSQL error 22012?

Most often this happens when dividing by a column or expression that evaluates to 0, or when aggregating a ratio where the denominator sum is 0.

How do I fix PostgreSQL error 22012?

Use NULLIF(divisor, 0) so the division yields NULL instead of error.

Which frameworks have documented fixes for error 22012?

This page documents fixes for: sqlalchemy, supabase.

Official Sources

This page is based on the official PostgreSQL documentation linked below and adds practical troubleshooting guidance on top.