2

Suppose I have a table named "Expense" and it has some month-wise expense which may contain some "NULL", now I want to check the yearly expenses in total with this below query:-

enter image description here

Select Sum(January) + Sum (February) ..... (I skipped the rest 10 months)
from Expense 

This gives result as "NULL"

How can I avoid this situation? I think there are more convenient way to check the yearly sum

1
  • 1
    SUM(IIF(Col IS NULL, 0, Col)) Commented Oct 8, 2018 at 8:17

7 Answers 7

4

All arithmetic or logical operations involving NULL yield NULL. For example:

SELECT 1 + NULL -- NULL

You must convert NULL to zeros before you can + them:

SELECT
    COALESCE(SUM(January), 0) +
    COALESCE(SUM(February) , 0) +
    ...

It is also possible to add the columns first and then calculate the sum:

SELECT SUM(
    COALESCE(January, 0) +
    COALESCE(February, 0) +
)

Be advised that (i) SUM skips NULL values (ii) returns NULL instead of 0 if all values are NULL:

SELECT SUM(a) FROM (VALUES
    (1),
    (2),
    (NULL)
) AS v(a) -- returns 3 instead of NULL

It will return NULL if all values encountered were NULL:

SELECT SUM(a) FROM (VALUES
    (CAST(NULL AS INT)),
    (NULL),
    (NULL)
) AS v(a) -- returns NULL instead of 0
Sign up to request clarification or add additional context in comments.

Comments

2

use coalesce function to convert null to 0 then use sum

Select Sum(coalesce(January,0)) + Sum (coalesce(February,0)) ..... (I skipped the rest 10 months)
from Expense

Comments

1

Just use coalesce [ with 0 as the second argument ] to replace nulls for all month columns, otherwise you can not get true results from aggregation of numeric values :

select sum(coalesce(January,0)+coalesce(February,0) ... )
  from Expense

Comments

0

That because you have NULL values, you can use Case, Coalesce or IIF:

Select SUM(IIF(Col IS NULL, 0, Col))

Select SUM(CASE WHEN Col IS NULL THEN 0 ELSE Col END)

Select COALESCE(Sum(Col), 0)

Comments

0

Any arithmetic function will return null if there is at least one null value in the given column. That's why you should use functions like coalesce or isNull (MSSQL), NVL (Oracle).

Comments

0

You can use ISNULL(SUM(January),0).

Comments

0

Because null + value is always null and in your sample some months sums are null, you can avoid this by adding ISNULL

Select isnull(Sum(January),0) + 
    isnull(Sum(February),0) 
--..... (I skipped the rest 10 months)
from Expense 

Alternatively you can use below way:

Select Sum(
    isnull(January,0) + 
    isnull(February,0) 
    )
--..... (I skipped the rest 10 months)
from Expense 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.