Discuz教程网

How do you specify difference between count(*) and count(1) in。。。

[复制链接]
authicon good 发表于 2010-10-26 08:05:53 | 显示全部楼层 |阅读模式

不知道大家有没有注意这个问题,平时都怎么写这个query
看完这里,一句话,使用count(*),,
By  Rudy Limeback, SQL Consultant, r937.com
SearchOracle.com
Digg This Stumble Delicious
How do you specify difference between count(*) and count(1) in a select statement? Which is best to use and when?
The difference is simple: COUNT(*) counts the number of rows produced by the query, whereas COUNT(1) counts the number of 1 values. Note that when you include a literal such as a number or a string in a query, this literal is "appended" or attached to every row that is produced by the FROM clause. This also applies to literals in aggregate functions, such as COUNT(1). It's hard to imagine a scenario where the COUNT(*) and COUNT(1) values would be different, so please do let me know if you find one.
In general, you should always use COUNT(*). This is because the database can often count rows by accessing an index, which is much faster than accessing a table. If you use COUNT(column), the database must actually inspect the individual values in the column, since it will not count NULLs. Aggregate functions like COUNT and SUM always ignore NULLs.
One would like to assume that the database optimizer is smart enough to realize that the literal value 1 will never be NULL, and not need to inspect it on every row, but it also would not surprise me to find out that the actions of appending the 1s into every row produced by the FROM clause and counting the 1s are handled by two separate logic modules, and maybe the module doing the counting doesn't know where the 1s came from. So just use COUNT(*).
17 Jan 2007



上一篇:dataguard 日志传输原理LGWR RSYNC,请大家指点
下一篇:求教:两个oracle数据库系统A和B,B查询统计数A的数据问题。
authicon duolanshizhe 发表于 2010-10-26 08:08:31 | 显示全部楼层

恩   很难区分
authicon renxiao2003 发表于 2010-10-26 08:53:40 | 显示全部楼层

好像count(*)的效率比count(1)高些。
authicon kakasi 发表于 2010-10-26 09:41:56 | 显示全部楼层
好像count(*)的效率比count(1)高些。
renxiao2003 发表于 2010-10-13 18:02
文章的作者是这么分析的,不过我一只图省事写count(1),没想到啊,呵呵
authicon renxiao2003 发表于 2010-10-26 09:50:09 | 显示全部楼层

回复 4# kakasi
    其实你还可以使用count(column_name),其中的列名是你的索引列。
authicon kakasi 发表于 2010-10-26 10:51:29 | 显示全部楼层
回复  kakasi
    其实你还可以使用count(column_name),其中的列名是你的索引列。
renxiao2003 发表于 2010-10-13 20:19
嗯,这个就是查非null个数了。
一直有误区,以为放了*进去会多搞出很多开销,而想当然的使用了常量1的话,会快些。看了这位老兄的分析,觉得挺有道理,,
不过话说回来,一个查数,慢也慢不到哪里去哈:mrgreen:
authicon renxiao2003 发表于 2010-10-26 11:17:55 | 显示全部楼层

呵呵。要是量大你就看出性能优劣来了。
authicon 拿钱发帖死全家 发表于 2010-10-26 11:55:52 | 显示全部楼层

一般用count(*)就行,假设数据比较多,或者有一列是有索引的,则可以把*替换为列名,性能会好些
authicon duolanshizhe 发表于 2010-10-26 12:19:59 | 显示全部楼层

假设要计数  count(pk column)应该是效率最高、准确度最高的做法
authicon wodi1015 发表于 2010-10-26 12:39:21 | 显示全部楼层

select /*index_ffs*/ count(index_column) from table
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

1314学习网 ( 浙ICP备10214163号 )

GMT+8, 2025-5-2 20:07

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表