Is it safe to use SUM() without ISNULL()

后端 未结 4 861
轮回少年
轮回少年 2021-02-18 14:14

I am trying to hence the performance of an SP. I have a doubt in my mind about SUM and ISNULL. When I sum up a column, should I use ISNULL? Is it SAFE to use SUM() without ISNUL

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-18 15:03

    Updated

    If you have [1, 2, NULL, 5] in 4 columns, it will give the output as 8.

    However, it is not safe to use SUM() without checking for NULLS in many cases.

    You can receive null when it has no matching content for a given clause. And if you are using this SUMMED value in another function, that maybe a point of concern.

    More details here: https://msdn.microsoft.com/en-GB/library/ms187810.aspx

    Please also look at COALESCE method https://msdn.microsoft.com/en-IN/library/ms190349.aspx

    PS: Also check out this post - My Select SUM query returns null. It should return 0

    Here are 3 images that shows without checking for NULL it returns NULL and not 0.

    SUM with ISNULL CHECK

    SUM without ISNULL CHECK

    SUM with COALESCE

提交回复
热议问题