[FIXED] Select Count(*) vs Select Count(id) vs select count(1). Are these indeed equivalent?

Issue

As a follow up to my earlier question:

Some of the answers and comments suggest that

select count(*) is mostly equivalent to select count(id) where id is the primary key.`

I have always favored select count(1); I even always use if exists (select 1 from table_name) ...

Now my question is:

1) What is the optimal way of issuing a select count query over a table?

2) If we add a where clause: where msg_type = X; if msg_type has a non_clustered index, would select count(msg_type) from table_name where msg_type = X be the preferred option for counting?

Side-bar:

From a very early age, I was taught that select * from... is BAD BAD BAD, I guess this has made me skeptical of select count(*) as well


Solution

count(*)  --counts all values including nulls

count(id)-- counts this column value by excluding nulls

count(1) is same as count(*)

If we add a where clause: where msg_type = X; if msg_type has a non_clustered index, would select count(msg_type) from table_name where msg_type = X be the preferred option for counting?

As i mentioned in my previous answer ,SQL server is a cost based optimizer and the plan choosen depends on many factors .sql tries to retrieve cheapest plan in minimum time possible..

now when you issue,count(msg_type),SQL may choose this index if this is cheaper or scan another one as long as it gives right results(no nulls in output)..

I always tend to use count(*) ,unless i want to exclude nulls



Answered By - TheGameiswar
Answer Checked By - Willingham (sql.easybugfix Volunteer)

Related Posts

Post a Comment