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 ISNULL. My example is below
SUM(ISNULL(COL1,0))
Since ISNULL costs a lot, I intend to use SUM without ISNULL like below
SUM(COL1)
I did some small tests and I couldnt see results
In MySQL, SUM() is supposed to ignore null values. In any case, if you want to be specific, you can instruct the SQL Optimiser to substitute the null values with the value of 0.
MySQL and PostgreSQL cannot sum up NULL values with the + value. The sum value will be NULL . If you want to do additions in the database: use SUM if it's an option to sum up a column of a result set instead of expressions ( SUM ignores NULL values)
If there are no rows, sum() will return null . It will also return null if all rows have a null balance.
You wrap the SUM with an ISNULL, ISNULL(Sum(Ac_Billbook. CostsNet), 0) because SUM ignores nulls when summing or you can reverse the SUM and ISNULL like this, Sum(ISNULL(Ac_Billbook. CostsNet, 0)) which will convert individual NULL's to 0. Doesn't really matter which one you do.
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
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.
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
Its better to use COALESCE method before the SUM aggregation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With