11

I am wondering whether SQL Server knows to 'cache' if you like aggregates while in a query, if they are used again.

For example,

Select Sum(Field),
       Sum(Field) / 12
From   Table

Would SQL Server know that it has already calculated the Sum function on the first field and then just divide it by 12 for the second? Or would it run the Sum function again then divide it by 12?

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

3 Answers3

9

It calculates once

Select
   Sum(Price),
   Sum(Price) / 12
From
   MyTable

The plan gives:

|--Compute Scalar(DEFINE:([Expr1004]=[Expr1003]/(12.)))
  |--Compute Scalar(DEFINE:([Expr1003]=CASE WHEN [Expr1010]=(0) THEN NULL ELSE [Expr1011] END))
     |--Stream Aggregate(DEFINE:([Expr1010]=Count(*), [Expr1011]=SUM([myDB].[dbo].[MyTable].[Price])))
        |--Index Scan(OBJECT:([myDB].[dbo].[MyTable].[IX_SomeThing]))

This table has 1.35 million rows

Community
  • 1
  • 1
gbn
  • 422,506
  • 82
  • 585
  • 676
3

According to the execution plan, it doesn't re-sum the column.

Neil Knight
  • 47,437
  • 25
  • 129
  • 188
-3

good question, i think the answer is no, it doesn't not cache it.

I ran a test query with around 3000 counts in it, and it was much slower than one with only a few. Still want to test if the query would be just as slow selecting just plain columns

edit: OK, i just tried selecting a large amount of columns or just one, and the amount of columns (when talking about thousands being returned) does effect the speed.

Overall, unless you are using that aggregate number a ton of times in your query, you should be fine. Push comes to shove, you could always save the outcome to a variable and do the math after the fact.

Limey
  • 2,642
  • 6
  • 37
  • 62
  • -1 - The time could be an indication of how long it takes to render the results, or pull the 3000 occurances of the same value from memory, and has no indication of if the result is cached or not. – JNK Jun 28 '11 at 14:29
  • OK but the first line of your answer is still factually and demonstrably incorrect, so the downvote stays. – JNK Jun 28 '11 at 14:37
  • "I think the answer is no", you take that as a statement of fact? – Limey Jun 28 '11 at 14:42
  • 1
    regardless of how you spin it, "no" is an incorrect answer to this question. – JNK Jun 28 '11 at 14:43