2

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.

1
  • not having access to postgres, but try coalesce(7/2,0.0) and see if that changes anything. sneaky suspicion it might be imposing int output since 0 is an int. Commented Aug 23, 2012 at 20:20

3 Answers 3

5

You need to do something like:

SELECT COALESCE((1.0 * 7)/2, 0) AS foo; 
Sign up to request clarification or add additional context in comments.

Comments

4

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

4 Comments

sooo...how do I get 3.5 out of it I'm still unsure.
Would you submit that query result to your boss? :) You just reproduced 3.0 instead of 3.5 which is the right result. I read that division (integer division truncates the result) but how do you get a right division result in this situation? Jack please submit your answer. It's the right one.
0_o What do you mean by "the right result"? PostgreSQL has integer division. Other languages don't. If you need floating point division, cast appropriately.
@GigiContra - And just what do you mean by "would you submit that query result to your boss"?
0

This feels better:

select 7.0/2.0; -------------------- 3.5000000000000000 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.