Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid division by zero in PostgreSQL

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?

like image 632
William Wino Avatar asked Jul 16 '13 15:07

William Wino


2 Answers

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

like image 183
Yuriy Galanter Avatar answered Sep 19 '22 19:09

Yuriy Galanter


Since count() never returns NULL (unlike other aggregate functions), you only have to catch the 0 case (which is the only problematic case anyway). So, your query simplified:

CASE count(column_name)    WHEN 0 THEN 1    ELSE count(column_name) END 

Or simpler, yet, with NULLIF(), like Yuriy provided.

Quoting the manual about aggregate functions:

It should be noted that except for count, these functions return a null value when no rows are selected.

like image 24
Erwin Brandstetter Avatar answered Sep 20 '22 19:09

Erwin Brandstetter