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?
If there are no rows, sum() will return null . It will also return null if all rows have a null balance.
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) ...
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.
SUM can be used with numeric columns only. Null values are ignored.
Try this:
select COALESCE(sum(balance),0) from mytable where customer = 'john'
This should do the work. The coalesce method should return the 0.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With