COUNT SQL 函数的性能
当使用 COUNT
函数编写 SQL 语句时,我有两种选择。
SELECT COUNT(*) FROM
SELECT COUNT(some_column_name) FROM
就性能而言,最好的 SQL 语句是什么? 使用选项 1 可以获得一些性能提升吗?
I have two choices when writing an SQL statement with the COUNT
function.
SELECT COUNT(*) FROM <table_name>
SELECT COUNT(some_column_name) FROM <table_name>
In terms of performance, what is the best SQL statement?
Can I obtain some performance gain by using option 1?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
性能并不重要,因为它们执行 2 个不同的聚合
COUNT(*)
是所有行,包括 NULLCOUNT(some_column_name)
,排除“some_column_name
”中的 NULL >"有关详细信息,请参阅“Count(*) 与 Count(1)”问题
Performance should not matter because they do 2 different aggregates
COUNT(*)
is all rows, including NULLsCOUNT(some_column_name)
, excludes NULL in "some_column_name
"See the "Count(*) vs Count(1)" question for more
选项 2 实际上会计算
some_column_name
不为 null 的所有字段。选项 1 对任意字段不为空的所有字段进行计数。因此,您实际上可能从这两个查询中得到不同的结果。大多数时候,您实际上想要对所有行进行计数,然后最快的选项(不检查任何字段)就是SELECT COUNT(1) FROM ...
Option 2 actually counts all the fields where
some_column_name
is not null. Option 1 counts all the fields where any field is not null. So you might actually get different results out of these two queries. Most of the time you actually want to count all the rows, and then the fastest option, which does not check for any of the fields, is simplySELECT COUNT(1) FROM ...
不,Sql Server 没有性能提升。
No, there is no performance gain in Sql Server.