views:

331

answers:

4

Hi All,

I have two choices when writing a SQL statement with COUNT function.

  1. SELECT COUNT(*) FROM
  2. SELECT COUNT(some_column_name) FROM

In terms of performance what is the beast SQL statement? can I obtain some performance gain by using option: 1 ?

Thanks, Upul

+1  A: 

No, there is no performance gain in Sql Server.

astander
+4  A: 

Option 2 actually counts all the fields where some_column_name is not null. Option 1 counts all the fields where any field is not null. So you might actually get different results out of these two queries. Most of the time you actually want to count all the rows, and then the fastest option, which does not check for any of the fields, is simply SELECT COUNT(1) FROM ...

David Hedlund
See this for COUNT(*) vs COUNT(1) http://stackoverflow.com/questions/1221559/
gbn
Count(*) also counts ALL rows, not just rows where any value is not null. And in terms of performance, Count(*) and Count(1) is the same, since the query optimizer recognizes what you are trying to do and generates the same execution plan.
Maximilian Mayerl
+7  A: 

It does not matter because they do 2 different aggregates

  • COUNT(*) is all rows, including NULLs
  • COUNT(some_column_name), excludes NULL in "some_column_name"

See "Count(*) vs Count(1)" question

gbn
A: 

You can visit a similar question..

StackOverflow

Hope this helps you... :-)

Richie