Count(*) or Count(1) that is the question.
For many years on Oracle’s forums there has been ideological fight: COUNT(*) or COUNT(1). Each option has its true believers and opponents.
The most common argument of group which supports the use of count(1) is the assertion that COUNT(1) is faster than COUNT(*). According to this theory COUNT(*) takes all columns to count rows and COUNT(1) counts using the first column: Primary Key. Thanks to that COUNT(1) is able to use index to count rows and it’s much faster.
It sounds reasonable, isn’t it? Unfortunately it is simply not true.
It’s time to dispel this widely spread myth.
The general definition of the COUNT function looks like the following:
COUNT function counts all of not empty (non-null) occurrences of expression <expression>.
COUNT(1) is nothing other than COUNT(<expression>) where the Expression = 1 => and „1” is obviously not null.
There is not too much to explain – it just counts all records in table.
As you can see count(1), count(‘banana’) and count(*) do the same thing. So maybe we should use COUNT(‘banana’)?
If you want to have clear and comprehensible code COUNT(*) is more appropriate. COUNT(*) at first glance indicates what will be done. Asterix is a typical sign of a meaning „everything” so you can assume that the function counts ALL rows.
As shown by stormy discussion on forums, COUNT(1) is not so obvious. If function COUNTS only the first column or the non null values or uses index? Opinions are divided and each version has its die-hard followers.
To sum up – if you want to count all the rows in a table you should use COUNT(*). If you want to count not null occurrences in a table – the best solution is COUNT(<expression>).
Finally, for all the sceptics, the last argument – all of you, no matter what you do, you end up doing COUNT(*) – Oracle internally rewrite COUNT(1) to COUNT(*).
Links to heated debates:
This post was published originally at my blog, which you can find here how2ora.blogspot.com.