When we execute select count(*) from table_name it returns the number of rows.
What does count(1) do? What does 1 signifies over here? Is this same as count(*) as it gives the same result on execution?
When we execute select count(*) from table_name it returns the number of rows.
What does count(1) do? What does 1 signifies over here? Is this same as count(*) as it gives the same result on execution?
This is similar to the difference between SELECT * FROM table_name and SELECT 1 FROM table_name. If you do SELECT 1 FROM table_name it will give you the number 1 for each row in the table. So yes count(*) and count(1) will provide the same results as will count(8) or count(column_name)
There is no difference.
COUNT(1)
is basically just counting a constant value 1 column for each row. As other users here have said, it's the same as COUNT(0)
or COUNT(42)
. Any non-NULL
value will suffice.
http://asktom.oracle.com/pls/asktom/f?p=100:11:2603224624843292::::P11_QUESTION_ID:1156151916789
The Oracle optimizer did apparently use to have bugs in it, which caused the count to be affected by which column you picked and whether it was in an index, so the COUNT(1) convention came into being.
The parameter to the COUNT function is an expression that is to be evaluated for each row. The COUNT function returns the number of rows for which the expression evaluates to a non-null value. ( * is a special expression that is not evaluated, it simply returns the number of rows.)
There are two additional modifiers for the expression: ALL and DISTINCT. These determine whether duplicates are discarded. Since ALL is the default, your example is the same as count(ALL 1), which means that duplicates are retained.
Since the expression "1" evaluates to non-null for every row, and since you are not removing duplicates, COUNT(1) should always return the same number as COUNT(*).
SELECT COUNT(1) should do the exact same thing as SELECT COUNT(*).
There may have been or still be some reasons why it would perform better than SELECT COUNT(*) on some database, but I would consider that a bug in the DB.
SELECT COUNT(col_name) however has a different meaning, as it counts only the rows with a non-null value for the given column.
Depending on who you ask, some people report that executing select count(1) from random_table;
runs faster than select count(*) from random_table
. Others claim they are exactly the same.
This link claims that the speed difference between the 2 is due to a FULL TABLE SCAN vs FAST FULL SCAN.