PostgreSQLERROR 22012
PostgreSQL: Division by Zero
PostgreSQL 22012 is raised when an arithmetic expression divides by zero. Unlike some databases, PostgreSQL does not silently return NULL — it raises an error and aborts the statement.
Example Query
SELECT total_sales / num_transactions FROM reports; -- Fails when num_transactions = 0
Common Causes
- 1Dividing by a column that can contain zero
- 2Dividing by a calculated expression that evaluates to zero
- 3Aggregate result (e.g. COUNT) used as divisor before filtering out empty groups
How to Fix It
Use NULLIF to avoid division by zero: total_sales / NULLIF(num_transactions, 0). This returns NULL instead of raising an error. Wrap with COALESCE to substitute a default: COALESCE(total / NULLIF(denom, 0), 0).
Need a reliable database?
Try Supabase — free PostgreSQL with a generous free tier. No credit card required.
Got a query causing this error?
Paste it into SQLbuddy and get an instant plain-English explanation with optimization tips.
Analyze My Query →