I have simple table (test) where I need to perform some additions (I want to get a row total and a column total).
id var1 var2
1 NULL NULL
2 10 NULL
For column totals, summing works as expected (NULL is ignored in the addition):
SELECT SUM(var1) FROM test
10
For row totals, addition does not ignore NULL (if any column is NULL the result is NULL):
SELECT var1+var2 FROM test
NULL
NULL
What I want it to return is:
SELECT var1+var2 FROM test
NULL
10
Is there a way to get MySQL to treat NULL as 0 in an addition?
You want to use coalesce()
:
select coalesce(var1, 0) + coalesce(var2, 0)
coalesce()
is ANSI standard and available in most databases (including MySQL).
use the IFNULL
function
SELECT IFNULL(var1, 0) + IFNULL(var2, 0) FROM test
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