SQL SERVER – Difference between COUNT(DISTINCT) vs COUNT(ALL)

Posted by pinaldave on SQL Authority See other posts from SQL Authority or by pinaldave
Published on Tue, 08 Mar 2011 01:30:03 +0000 Indexed on 2011/03/08 8:13 UTC
Read the original article Hit count: 470

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
FROM [AdventureWorks].[Person].[Contact]
GO
SELECT COUNT(ALL [Title]) ALLValue
FROM [AdventureWorks].[Person].[Contact]
GO
SELECT COUNT(DISTINCT [Title]) DistinctValue
FROM [AdventureWorks].[Person].[Contact]
GO

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)


Filed under: Pinal Dave, PostADay, SQL, SQL Authority, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, SQLAuthority News, T SQL, Technology

© SQL Authority or respective owner

Related posts about Pinal Dave

Related posts about PostADay