PostgreSQL error: division by zero
ERROR: division by zero
Some division (or modulo) in the query hit a zero denominator. Unlike some databases and most floating-point environments, PostgreSQL raises an error rather than returning NULL or infinity — so any division whose denominator can be zero needs to say what should happen.
What this error means
The error aborts the whole statement (and the transaction), even if only one row out of millions had the zero. That is why it typically appears in aggregations and reports: everything works until the first day a group is empty or a total is zero. The fix is almost always the same idiom, applied at the division site.
Common causes
- Rates and percentages where the denominator comes from data:
clicks / impressions,revenue / orders— fine until a zero row shows up. - Percent-change against a zero baseline.
- Zero from an aggregate or COALESCE:
count(*) FILTER (...)orCOALESCE(x, 0)feeding a denominator.
How to diagnose it
Find the divisions in the query and ask which denominator can be zero. To see the offending rows, select the denominator expression with its grouping keys and filter for zero — the rows that come back are the ones that will explode the division.
How to fix it
-- L'idioma standard: denominatore zero → risultato NULL
SELECT clicks / NULLIF(impressions, 0) AS ctr FROM stats;
-- Se vuoi 0 (o altro default) invece di NULL:
SELECT COALESCE(clicks / NULLIF(impressions, 0), 0) AS ctr FROM stats;
NULLIF(x, 0)turns the zero into NULL, and division by NULL yields NULL instead of an error. Decide deliberately whether NULL ("undefined") or a default is right for the report.- Adjacent trap while you are here: integer division truncates —
1/2 = 0. Cast one side (clicks::numeric / NULLIF(impressions, 0)) when you want fractions.
