Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

Bradley Schacht

Bradley is a consultant at Pragmatic Works in Jacksonville, FL. He was an author on the book SharePoint 2010 Business Intelligence 24-Hour Trainer and tech edited the SQL 2011 Bible. His experience on the Microsoft BI platform includes DTS, SSIS, SSRS, SSAS and migrations and conversions. He has helped numerous companies in successfully developing and implementing new business intelligence solutions into their organizations. Bradley also participates as a speaker in community events like SQL Saturday, Code Camp, SQL Lunch and SQL Server User Groups. He is a contributor on sites such as BIDN.com and SQL Server Central as well as an active member of the Jacksonville SQL Server User Group (JSSUG).

SELECT COUNT(*) vs COUNT(1) vs COUNT(ColumnName)

What is the difference between COUNT(*), COUNT(1) and COUNT(ColumnName)? A mystery that will never be known… ok that was a lie, but the rest of this blog is not a lie, just to be clear.  :)

COUNT(*) – Number of records in the table regardless of NULL values and duplicates
COUNT(1) – Number of records in the table regardless of NULL values and duplicates **IMPORTANT NOTE: The 1 does NOT refer to an ordinal location of a column. This will not count the records in the first column of the table as COUNT(ColumnName) does.**
COUNT(ColumnName) or COUNT(ALL ColumnName) – Number of non-NULL values
COUNT(DISTINCT ColumnName) – Number of distinct non-NULL values

I ran counts on a pretty good size table of 13+ million records and came up with both COUNT(*) and COUNT(1) executing with the same CPU time and elapsed time. Occasionally COUNT(*) would have a higher CPU time and sometimes COUNT(1) would have a higher CPU time. But neither was drastically different from the other. In addition to the statistics from the run if you look at the execution plans for both of these two they will be the exact same, providing further evidence that they behave the same. So from what I can conclude and have read from other sources online they are both essentially the same thing.

Conclusion: COUNT(*) and COUNT(1) are the same.

From what I understand this MAY have been an issue with Oracle where the query engine would treat them different, but I can’t confirm that just thought I would toss it out there for argument sake. Those same sources also say that has been resolved and they both function the same now. Also note that COUNT_BIG works exactly the same as COUNT it just returns the value in the form of a big integer instead of a regular integer.

Have you seen these same results or do you have evidence to the contrary?  Sound off in the comments!

Comments

No comments.

Leave a Comment

Please register or log in to leave a comment.