Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / SQL

SQL COUNT(*) Vs COUNT(column_name)

4.00/5 (5 votes)
30 Apr 2010CPOL 38.8K  
In many case we need to use COUNT function, but always we prefer COUNT(column_name) in placeof COUNT(*) and reason behind that COUNT(column_name) will perform better or faster than COUNT(*).Is this correct?SQL Server can't read just the contents of a single column without reading the...
In many case we need to use COUNT function, but always we prefer COUNT(column_name) in place
of COUNT(*) and reason behind that COUNT(column_name) will perform better or faster than COUNT(*).

Is this correct?

SQL Server can't read just the contents of a single column without reading the entire row.
So that if we use COUNT(column_name) then also SQL needs to read an entire page from memory just to check a single column of a row.

Let we discuss another case.
We use COUNT(column_name) to count the number of rows of a table where column name is a column that does not allow NULL values.
Now suppose after some time definition of this column gets changed and it is allowing null values, so now column may contain null values.
We may not expect the above situation, and it could possibly cause major problems.

SQL
Now try this

SET STATISTICS IO ON
SELECT COUNT(*) FROM Table_Name
SELECT COUNT(column_name) FROM Table_Name
SET STATISTICS IO OFF


when you see the result and read messages you are also agree with my opinion.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)