Home Forums SQL Server 7,2000 T-SQL SELECT COUNT(*) or COUNT(1) Performance or Benefits? RE: SELECT COUNT(*) or COUNT(1) Performance or Benefits?

  • Yes, you are right in that the queries return different results. The reasons were also mentioned earlier in this thread and in my article. As noted the reason is that COUNT(expression), where expression might simply be the name of a column, does not count occurences where expression evaluates to null. Since COUNT(*) counts every row, there is no concept of null involved (if there is a row then there is one, no matter how many of the columns on it that are null, or even might be) and therefore the results might differ. From the results we can see that there are 91 rows in the table Northwind.dbo.Customers, of which 60 (91-31) do not have a value (they are null) for column Region and 22 (91-69) do not have a value for column Fax.

    You are also correct in that whether a column allows nulls or not might affect which execution plan is chosen. If a column that does not allow nulls is used as the expression, such as COUNT(CustomerId), this has the same meaning as COUNT(*) since all rows should be counted. Therefore the same plans will be used. If it does allow null then there might be rows with null and therefore the expression must be evaluated for each row (here evaluated means that the value of the column must be checked). If there is an index on the column then a scan of that index will be used (as in the COUNT(Region) example query), and if there is not an index then a table scan/clustered index scan will be used (as with the COUNT(Fax) example).

    However, to finally get back to why I asked you to elaborate, I think you have misunderstood COUNT(1). The 1 does not indicate the ordinal number of a column, it is simply an expression that will always be true. So COUNT(*) and COUNT(1) will never return different results and will always use the same plan, since they are treated as identical queries by the optimizer.