Search code examples
performancet-sqlsql-server-2012aggregate-functionssql-types

Why SUM is faster when we are using SMALLINT instead DECIMAL


Are there any known rules saying some T-SQL types are better for calculations?

I have two identical tables containing numbers - one with SMALLINT fields and second with DECIMAL(9,2) fields. I am performing the following operations over them (two queries):

SUM(CAST(A AS BIGINT))
SUM(CAST(A AS BIGINT))
CAST(CAST(SUM(A) AS decimal) / CASE SUM(B) WHEN 0 THEN NULL ELSE SUM(B) END * 100 AS decimal(18, 0))
CAST(CAST(SUM(A) AS decimal) / CASE SUM(B) WHEN 0 THEN NULL ELSE SUM(B) END * 100 AS decimal(18, 1)) 

SUM(CAST(A AS DECIMAL(19,2))) 
SUM(CAST(A AS DECIMAL(19,2)))
CAST(SUM(CAST([A] AS DECIMAL(19, 2))) / IIF(SUM(CAST([B] AS DECIMAL(19, 2))) = 0, NULL, SUM(CAST([B] AS DECIMAL(19, 2)))) * 100 AS DECIMAL(19, 0))
CAST(SUM(CAST([A] AS DECIMAL(19, 2))) / IIF(SUM(CAST([B] AS DECIMAL(19, 2))) = 0, NULL, SUM(CAST([B] AS DECIMAL(19, 2)))) * 100 AS DECIMAL(19, 1))

and there the query results are about:

  • 29 seconds for the table with decimal columns
  • 18 seconds for the table with smallint columns

The only difference is in the byes for each type:

Is this the reason SMALLINT is faster then DECIMAL(9,2) for such operations?

Note: I have the same values in each tables - I have not got decimal numbers - only whole numbers.


Solution

  • Yes, that's true. Smallint values need less space on disk and the IO operation have much more performance. It's always a good idea to have as 'small' type as it is possible.