8

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?

2

3 Answers 3

26

You want to use coalesce():

select coalesce(var1, 0) + coalesce(var2, 0)

coalesce() is ANSI standard and available in most databases (including MySQL).

Sign up to request clarification or add additional context in comments.

1 Comment

This is more portable than the other solutions
13

use the IFNULL function

SELECT IFNULL(var1, 0) + IFNULL(var2, 0) FROM test

Comments

0
select 
Case when (coalesce(`var1`, 0) + coalesce(`var2`, 0))=0
then NULL
else coalesce(`var1`, 0) + coalesce(`var2`, 0)
end
from test

SQL FIDDLE

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.