1. 程式人生 > >Oracle 中count(1) 、count(*) 和count(列名) 函數的區別

Oracle 中count(1) 、count(*) 和count(列名) 函數的區別

select sdn 快的 包含 varchar2 into 要去 tails lan

1)count(1)與count(*)比較:

1、如果你的數據表沒有主鍵,那麽count(1)比count(*)快
2、如果有主鍵的話,那主鍵(聯合主鍵)作為count的條件也比count(*)要快
3、如果你的表只有一個字段的話那count(*)就是最快的啦
4、count(*) count(1) 兩者比較。主要還是要count(1)所相對應的數據字段。
5、如果count(1)是聚索引,id,那肯定是count(1)快。但是差的很小的。 因為count(*),自動會優化指定到那一個字段。所以沒必要去count(?),用count(*),sql會幫你完成優化的

2)count詳解:

1、count(*)將返回表格中所有存在的行的總數包括值為null的行,然而count(列名)將返回表格中除去null以外的所有行的總數(有默認值的列也會被計入).
2、distinct 列名,得到的結果將是除去值為null和重復數據後的結果


3)舉例演示如下:

 1 SQL> create table test
 2 (
 3 ename varchar2(10),
 4 sal number(4)
 5  );
 6 
 7 表已創建。
 8 
 9  
10 SQL> insert into test values(fxe1,90);
11 已創建 1 行。
12  
13 SQL> insert into test(ename) values(fxe2);
14 已創建 1 行。
15 
16 SQL> insert into test(ename) values(fxe3);
17 已創建 1
行。 18 19 SQL> insert into test(ename) values(fxe4); 20 已創建 1 行。 21 22 SQL> insert into test values(fxe5,80); 23 已創建 1 行。 24 25 SQL> insert into test values(fxe6,80); 26 已創建 1 行。 27 28 29 SQL> select * from test; 30 ENAME SAL 31 ---------- ---------- 32 fxe1 90 33 fxe2
34 fxe3 35 fxe4 36 fxe5 80 37 fxe6 80 38 39 40 SQL> select count(*) from test; -- count(*):包含NULL,一共6條記錄 41 COUNT(*) 42 ---------- 43 6 44 45 SQL> select count(1) from test; -- count(1):包含NULL,一共6條記錄,和count(*)的結果一樣 46 COUNT(1) 47 ---------- 48 6 49 50 SQL> select count(sal) from test; -- count(列名):不包含NULL,但包含重復值項,一共3條記錄 51 COUNT(SAL) 52 ---------- 53 3 54 55 SQL> select count(distinct sal) from test; -- count(列名):不包含NULL,去重“count(distinct sal)”,一共2條記錄 56 COUNT(DISTINCTSAL) 57 ------------------ 58 2 59 60 SQL> select distinct sal from test; 61 SAL 62 ---------- 63 80 64 90

轉至:http://blog.csdn.net/szstephenzhou/article/details/8446481

Oracle 中count(1) 、count(*) 和count(列名) 函數的區別