22012: division_by_zero
PostgreSQLWhat does it mean?
An arithmetic expression attempted division (or modulo) by zero. PostgreSQL does not allow division by zero and aborts the query.
Why does it happen?
The divisor column/expression evaluating to 0; a zero denominator in a ratio/percentage calculation; dividing by a COUNT or SUM that is zero; unexpected zero values in unfiltered data.
How to fix it
Use NULLIF to return NULL when the denominator is zero: numerator / NULLIF(denominator, 0). If desired, turn the result into a default with COALESCE: COALESCE(numerator / NULLIF(denominator,0), 0). Or use CASE WHEN denominator = 0 THEN NULL ELSE numerator/denominator END. Filter out zero cases in the data beforehand.