Click here to Skip to main content
15,879,239 members
Articles / Programming Languages / SQL
Tip/Trick

SQL COUNT(*) Vs COUNT(column_name)

Rate me:
Please Sign up or sign in to vote.
4.00/5 (5 votes)
30 Apr 2010CPOL 37.6K   5   3
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)


Written By
Software Developer (Senior)
India India
Hi, I am Samrat Banerjee from India.
I am a Software Engineer working in .net platform.
I love to explore new technologies.

Comments and Discussions

 
GeneralYou forget a major point: With SQL Server 2000, you must not... Pin
Bernhard Hiller6-May-10 23:48
Bernhard Hiller6-May-10 23:48 
GeneralIt will be good,if You explain the result message in detail.... Pin
Sundeep Ganiga3-May-10 18:09
Sundeep Ganiga3-May-10 18:09 
GeneralMy vote of 1 Pin
FZelle1-May-10 0:12
FZelle1-May-10 0:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.