This blog post is written in response to the T-SQL Tuesday hosted by Jes Schultz Borland. Earlier today, I was presenting a 45-minute session at the Community College about “The Beginning SQL Server Database”. One of the students asked me the following question.
What is the difference between COUNT(DISTINCT) vs COUNT(ALL)?
I found this question from the student very interesting. He seems to have read the documentation (Book Online) and was then asking me this question.
I always carry laptop which has SQL Server installed. I quickly opened it and ran the following script. After looking at the result, I think it was clear to everybody.
Here is the script:
SELECT COUNT([Title]) Value
SELECT COUNT(ALL [Title]) ALLValue
SELECT COUNT(DISTINCT [Title]) DistinctValue
The above script will give me the following results.
You can clearly notice from the result set that COUNT (ALL ColumnName) is the same as COUNT(ColumnName). The reality is that the “ALL” is actually the default option and it needs not to be specified. The ALL keyword includes all the non-NULL values.
I know this is very simple and may be it does not change how we work; however looking at the whole angle, I really enjoyed the question.
Reference: Pinal Dave (http://blog.SQLAuthority.com)