Avoid division by zero in PostgreSQL

William Wino picture William Wino · Jul 16, 2013 · Viewed 74.4k times · Source

I'd like to perform division in a SELECT clause. When I join some tables and use aggregate function I often have either null or zero values as the dividers. As for now I only come up with this method of avoiding the division by zero and null values.

(CASE(COALESCE(COUNT(column_name),1)) WHEN 0 THEN 1
ELSE (COALESCE(COUNT(column_name),1)) END) 

I wonder if there is a better way of doing this?

Answer

Yuriy Galanter picture Yuriy Galanter · Jul 16, 2013

You can use NULLIF function e.g.

something/NULLIF(column_name,0)

If the value of column_name is 0 - result of entire expression will be NULL