COUNT(*)與COUNT(列) 要看是否使用到索引以及索引列不為空,
不考慮索引的時候count(*) 反而更加快,
因為oracle最佳化器列偏移演算法的原因,越靠後的列越慢,
所以設計應用的時候,經常訪問的列應該放在前面
表無索引時,count()的效能
drop table t purge;
create table t as select * from dba_objects;
alter table T modify object_id null;
update t set object_id =rownum ;
set timing on
set linesize 1000
set autotrace on
表無索引時,count(*)的效能更好
SELECT count(*) from t;
表無索引時,count(列)的效能,這個列如果越靠後,效能越不好
select count(object_id) from t;
表有object_id列索引時,count(列)的效能很好
select count(object_id) from t;
——————————————————————————————————————————————
表有索引且索引列非空時,count(*)的結果與count(object_id)查詢結果一致,最佳化器自動把count(*)最佳化成count(object_id),所以這時候count(*)實質就是count(object_id),如果object_id允許為空,這時候count(*)的結果與count(object_id)查詢結果可能不一致,最佳化器改寫的前提是保證結果不出錯,會出錯的話,最佳化器絕對不會改寫。(object_id為空時不進行計數),這時候count(*)不會最佳化成count(object_id),查詢沒有count(object_id)快。
alter table T modify object_id not null;
select count(*) from t;——與下面的count(object_id)效果一致
表有索引且索引列非空時,count(列)的效能
select count(object_id) from t;
具體可以看看 《不止sql最佳化》最後一章節