PostgreSQL error 22012 (Division by Zero) explained: what it means, why it happens, and how to fix it — with copy-paste code examples.
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.
SQLSTATE: 22012
Official name: Division by Zero
Service: PostgreSQL
Division by zero was attempted.
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.
Use nullif() in the expression to short-circuit zero divisors.
from sqlalchemy import func, nullif
expr = col_a / nullif(col_b, 0)
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;
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.
Use NULLIF(divisor, 0) so the division yields NULL instead of error.
This page documents fixes for: sqlalchemy, supabase.
Recommendations are editorial — DB Error Reference takes no payment or affiliate fees for tool listings.
This page is based on the official PostgreSQL documentation linked below and adds practical troubleshooting guidance on top.