Count(*) 与 Count(1) - SQL Server [英] Count(*) vs Count(1) - SQL Server
问题描述
只是想知道你们中是否有人使用 Count(1)
而不是 Count(*)
并且性能上是否有明显差异,或者这是否只是遗留问题过去养成的习惯?
Just wondering if any of you people use Count(1)
over Count(*)
and if there is a noticeable difference in performance or if this is just a legacy habit that has been brought forward from days gone past?
具体数据库为SQL Server 2005
.
推荐答案
没有区别.
原因:
在线图书 说COUNT ( {[ [ ALL | DISTINCT ] 表达式 ] | * } )
"
"1" 是一个非空表达式:所以它与 COUNT(*)
相同.优化器认为它是什么:微不足道.
"1" is a non-null expression: so it's the same as COUNT(*)
.
The optimizer recognizes it for what it is: trivial.
与 EXISTS (SELECT * ...
或 EXISTS (SELECT 1 ...
示例:
SELECT COUNT(1) FROM dbo.tab800krows
SELECT COUNT(1),FKID FROM dbo.tab800krows GROUP BY FKID
SELECT COUNT(*) FROM dbo.tab800krows
SELECT COUNT(*),FKID FROM dbo.tab800krows GROUP BY FKID
同样的 IO,同样的计划,同样的作品
Same IO, same plan, the works
编辑,2011 年 8 月
Edit, Aug 2011
编辑,2011 年 12 月
Edit, Dec 2011
COUNT(*)
在 ANSI 中特别提到-92(查找标量表达式 125
")
案例:
a) 如果指定了 COUNT(*),则结果为 T 的基数.
a) If COUNT(*) is specified, then the result is the cardinality of T.
也就是说,ANSI 标准认为它很明显你的意思.COUNT(1)
已被 RDBMS 供应商优化掉因为这个迷信.否则将按照 ANSI 进行评估
That is, the ANSI standard recognizes it as bleeding obvious what you mean. COUNT(1)
has been optimized out by RDBMS vendors because of this superstition. Otherwise it would be evaluated as per ANSI
b) 否则,令 TX 为单列表,即应用<值表达式>的结果到 T 的每一行并消除空值.如果一个或多个空值是消除,然后引发完成条件:警告-
b) Otherwise, let TX be the single-column table that is the result of applying the <value expression> to each row of T and eliminating null values. If one or more null values are eliminated, then a completion condition is raised: warning-
这篇关于Count(*) 与 Count(1) - SQL Server的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!