Select Count(*) / Count(1) / Count(欄位名) 的差異

在T-SQL裡有個Count()函數,使用相當的廣泛,但Select Count(*),Select Count(1),Select Count(欄位名稱),這三種寫法有什麼差別?

在T-SQL裡有個Count()函數,使用相當的廣泛,但Select Count(*),Select Count(1),Select Count(欄位名稱),這三種寫法有什麼差別?

 

Count都是計算資料不是Null的筆數, Count(*)與Count(1)是一樣的,而Count(欄位名稱)所Count的結果,是只有那個欄位的非Null資料.

 

舉例來說 :

TableName : Test1

ColumnName

Type

TID

Int

LocTest

Varchar

內容如下 :

TID

LocTest

1

1

2

Null

3

2

Null

Null

Select Count(*) from Test1與Select Count(1) from Test1的結果一樣,回傳4

Select Count(LocTest) from Test1,結果就不一樣了,回傳2,因為TID=2與第四個TID=null的那筆LocTest是null.

TID=null的這筆比較奇怪,一般是不會有整筆資料全部是Null的,不過這裡只是想測試Count(*),是不是全部都為Null,那就不算,測試結果不是~

 

接下來,那麼Select Count(*) 與Select Count(1)又有什麼差別,「聽說」這兩個的差別是「效能」,又是一個令人眼睛為之一亮的字眼,是有找到一個比較好的解釋.

Since the COUNT function will return the same results regardless of what NOT NULL field(s) you include as the COUNT function parameters (ie: within the brackets), you can change the syntax of the COUNT function to COUNT(1) to get better performance as the database engine will not have to fetch back the data fields.

Select Count(*)是取回所有的欄位去Count,雖然我們只是看到Count的結果.

Select Count(1)一樣可以Count整個記錄,不過用的是一個實際的值,所以說,Select Count(‘Jeff-Yeh’)也是可以,一樣的效果,因此它的效能會比Count(*)好.

*所以別把Select Count(1)裡的數字,當做是欄位第一個..

 

做個測試Table,設個20個欄位,塞入1,000,000筆資料來看看,不搞大一點,真怕感覺不太出來,測個5次,看它的用戶端統計資料.

Select (*) :

clip_image002

Select (1) :

clip_image004

看了上述的結果還真的是”沒什麼差”,可能我測試的DB是SQL 2005,那天在不同DB遇到,再來試看看吧…

參考 : SQL: COUNT Function