My Select SUM query returns null. It should return 0
SqlSql ServerSql Problem Overview
I'm trying to sum up Customer balances using the following query:
select sum(balance) from mytable where customer = 'john'
However, if the customer has no balance (i.e. no matching rows in the mytable
table), my query returns null and not 0. What's the problem?
Sql Solutions
Solution 1 - Sql
Try this:
select COALESCE(sum(balance),0) from mytable where customer = 'john'
This should do the work. The coalesce method should return the 0.
Solution 2 - Sql
That's not a problem. If there are no rows, sum()
will return null
. It will also return null
if all rows have a null
balance.
To return zero instead, try:
select isnull(sum(balance),0) from mytable where customer = 'john'
Solution 3 - Sql
select coalesce(sum(coalesce(balance,0)),0) from mytable where customer = 'john'
Solution 4 - Sql
Maybe you are thinking of COUNT
's behaviours?
COUNT(Field)
will return 0
but SUM(Field)
returns NULL
if there are no matching rows.
You need an ISNULL
or COALESCE
Solution 5 - Sql
Try this:
select sum(IsNull(balance,0)) from mytable where customer = 'john'