Say I have a simple function in MySQL:
SELECT SUM(Column_1)
FROM Table
WHERE Column_2 = 'Test'
If no entries in Column_
2 contain the text 'Test' then this function returns NULL
, while I would like it to return 0.
I'm aware that a similar question has been asked a few times here, but I haven't been able to adapt the answers to my purposes, so I'd be grateful for some help to get this sorted.
if sum of column is 0 then display empty
select if(sum(column)>0,sum(column),'')
from table
Can't get exactly what you are asking but if you are using an aggregate SUM function which implies that you are grouping the table.
The query goes for MYSQL like this
Select IFNULL(SUM(COLUMN1),0) as total from mytable group by condition
SELECT IFNULL(SUM(Column1), 0) AS total FROM...
SELECT COALESCE(SUM(Column1), 0) AS total FROM...
The difference between them is that IFNULL
is a MySQL extension that takes two arguments, and COALESCE
is a standard SQL function that can take one or more arguments. When you only have two arguments using IFNULL
is slightly faster, though here the difference is insignificant since it is only called once.
Source: Stackoverflow.com