Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My Select SUM query returns null. It should return 0

Tags:

sql

sql-server

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?

like image 980
nec tso Avatar asked Jun 11 '13 15:06

nec tso


People also ask

Does SUM return NULL SQL?

If there are no rows, sum() will return null . It will also return null if all rows have a null balance.

What happens when you SUM NULL SQL?

In MySQL, SUM() is supposed to ignore null values. In any case, if you want to be specific, you can instruct the SQL Optimiser to substitute the null values with the value of 0. To do that, you can help yourself with the COALESCE() function and the following model: SELECT COALESCE(SUM(column_name), 0) ...

How do I avoid NULL values in SELECT query?

SELECT column_names FROM table_name WHERE column_name IS NOT NULL; Query: SELECT * FROM Student WHERE Name IS NOT NULL AND Department IS NOT NULL AND Roll_No IS NOT NULL; To exclude the null values from all the columns we used AND operator.

Does SQL SUM Ignore NULL?

SUM can be used with numeric columns only. Null values are ignored.


2 Answers

Try this:

select COALESCE(sum(balance),0) from mytable where customer = 'john'  

This should do the work. The coalesce method should return the 0.

like image 50
alwaysVBNET Avatar answered Sep 19 '22 17:09

alwaysVBNET


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'  
like image 29
Andomar Avatar answered Sep 19 '22 17:09

Andomar