Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgresql coalesce

Tags:

postgresql

Can anyone say why this select returns 3.0 instead of 3.5:

SELECT coalesce(1.0*(7/2),0) as foo

This one returns 3:

SELECT coalesce(7/2,0) as foo

I'm just trying to divide a SUM by COUNT to find an average. I need it 0 if null and 1 rounded by 1 decimal in case I have results.

like image 266
Gigi Contra Avatar asked Jun 01 '26 04:06

Gigi Contra


2 Answers

You need to do something like:

SELECT COALESCE((1.0 * 7)/2, 0) AS foo;
like image 166
clee Avatar answered Jun 04 '26 02:06

clee


Well, 7/2 is an integer, 1.0 is numeric, and so 1.0*(7/2)==1.0 * 3 == 3.0.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!