SQLTeam.com | Weblogs | Forums

Using cast inside sum or outside?

I work on sql server 2012 I face issue using cast first or sum ?
cast (sum(a) as decimal(18,2)
sum(cast (a as decimal(18,2)))
which is correct and more speed
a is nteger need to convert to decimal
so using cast inside sum or outside

It's more efficient to do the CAST after the SUM.

But, if the SUM would overflow the data type, then do the CAST before the SUM.

For example, you are adding a bunch of ints and total would exceed the max value for an int, then CAST to a bigint before doing the SUM.