[英]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? 是否有已知规则说某些T-SQL类型更适合计算?
I have two identical tables containing numbers - one with SMALLINT
fields and second with DECIMAL(9,2)
fields. 我有两个包含数字的相同表-一个具有
SMALLINT
字段,另一个具有DECIMAL(9,2)
字段。 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: 那里的查询结果是关于:
The only difference is in the byes for each type: 每种类型的唯一区别是:
Is this the reason SMALLINT
is faster then DECIMAL(9,2)
for such operations? 这是因为
SMALLINT
比DECIMAL(9,2)
更快的原因吗?
Note: I have the same values in each tables - I have not got decimal numbers - only whole numbers. 注意:我在每个表中都有相同的值-我没有十进制数字-只有整数。
Yes, that's true. 是的,这是真的。 Smallint values need less space on disk and the IO operation have much more performance.
Smallint值需要较少的磁盘空间,并且IO操作具有更高的性能。 It's always a good idea to have as 'small' type as it is possible.
尽可能具有“小”字型总是一个好主意。
From Microsoft's documentation : 从Microsoft的文档中 :
Converting from decimal or numeric to float or real can cause some loss of precision.
从十进制或数字转换为浮点数或实数会导致精度降低。 Converting from int, smallint, tinyint, float, real, money, or smallmoney to either decimal or numeric can cause overflow.
从int,smallint,tinyint,float,real,money或smallmoney转换为十进制或数字都可能导致溢出。
By default, SQL Server uses rounding when converting a number to a decimal or numeric value with a lower precision and scale.
默认情况下,SQL Server在将数字转换为精度和小数位数较低的十进制或数字值时使用舍入。 However, if the SET ARITHABORT option is ON, SQL Server raises an error when overflow occurs.
但是,如果SET ARITHABORT选项为ON,则在发生溢出时SQL Server会引发错误。 Loss of only precision and scale is not sufficient to raise an error.
仅精度和规模的损失不足以引起误差。
This strongly implies that extra operations surround decimal
arithmetic, specifically scaling, rounding, and range checking. 这强烈意味着额外的运算会围绕
decimal
算术,特别是缩放,舍入和范围检查。 All of those are substantially harder (more computation intensive) than addition, especially on an x86 CPU. 所有这些都比添加要难得多(计算强度更大),尤其是在x86 CPU上。
The fastest datatypes are those native to the CPU—usually char
and integer
— and should be fastest on most SQL platforms. 最快的数据类型是CPU固有的数据类型(通常是
char
和integer
,并且在大多数SQL平台上应该是最快的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.