I have to do a sum of 2 fields that are then also summed. Is there any difference from a performance standpoint between doing the addition of the fields first or after the columns have been summed?
Method 1 = SELECT SUM(columnA + columnB)
Method 2 = SELECT SUM(columnA) + SUM(columnB)
(Environment = SQL Server 2008 R2)
I have to do a sum of 2 fields that are then also summed.
Share
I have checked on this, and what i see is that the
sum(x) + sum(y)is faster.Why? When you use a sum function you are working with an aggregate function. When you are aggregating, null values will be skipped in such. When you are combining two fields in an aggregate function the processor has to check if one of the fields is NULL, since a set can contain both a value and a NULL. Adding NULL (or UNKNOWN or NOTHING if you like) to something, is still nothing, so NULL. So for each record this has to be checked.
When you look into your execution plan and you check on the computer scalar operator you’ll see exactly this behavior.
For the
sum(x) + sum(y)method you see a estimated cpu cost of 0,0000001 where the other method takes up to 0,0000041. That is something more!Also, when you take a closer look you’ll see that the
sum(x + y)will be made something like[Expr1004] = Scalar Operator(CASE WHEN [Expr1006]=(0) THEN NULL ELSE [Expr1007] END)So, eventually, the
sum(x) + sum(y)can be considered faster.