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

后端 未结 4 862
轮回少年
轮回少年 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 14:53

    Its not mandatory to use NULL and COALESCE while doing SUM because SUM always ignore null values.

    Refer the link : https://msdn.microsoft.com/en-IN/library/ms187810.aspx for more info.

    0 讨论(0)
  • 2021-02-18 15:00

    Its better to use COALESCE method before the SUM aggregation.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-18 15:05

    Yes its safe . You can use Sum without handling NULL Value. You can also check that.

    You can use like that also.

    ISNULL(SUM(COL1),0).

    Returns the sum of all the values, or only the DISTINCT values, in the expression. SUM can be used with numeric columns only. Null values are ignored.

    For Reference : https://msdn.microsoft.com/en-IN/library/ms187810.aspx

    0 讨论(0)
提交回复
热议问题