Addition with NULL values

I accomplished it this way:

coalesce("Column1",0.00) + coalesce("Column2",0.00)

I'm working with front end high level execs.... They don't understand why NULL and 0 aren't handled the same way.

In my case it works, just replacing NULLs with 0.00... may not in all though :)


If you want to add a and b and either may be null, you could use coalesce, which returns the first non-null parameter you pass it:

coalesce(a+b, a, b)

So in this case, if neither parameter is null, it will return the sum. If only b is null, it will skip a+b and return a. If a is null, it will skip a+b and a and return b, which will only be null if they are both null.

If you want the answer to be 0 rather than null if both a and b are null, you can pass 0 as the last parameter:

coalesce(a+b, a, b, 0)

Do consider @erwins answer - null might not be the right thing to be using.


You can also use ISNULL, so if you have 3 values

isnull(val1,0)+isnull(val2,0)+isnull(val3,0)

which ever column will have a NULL will use a 0, otherwise its original value.

Tags:

Sql

Null