I've always wondered what the difference is between these three ways of using COUNT
SQL (I also don't know if there is a difference depending on the database driver being used).
For example in MySQL, if I have a table with 100 records and I do this:
SELECT COUNT(*), COUNT(1), COUNT(columna) FROM tabla;
It throws me three columns with a correct count.
What is the difference between these three ways of using COUNT
?
Is there one of them, based on objective tests, that is more recommended or does it not matter to use any of the forms?
Regarding results:
There is no difference between
count(*)
andcount(1)
, for each returned row it will count 1 equally.But
count(columna)
it's different: it won't count rows where that column isNULL
.Also, in the latter case you can count only the distinct ones:
In terms of performance, it is difficult to say if one is better than another, since it depends on whether it is used alone or with more fields and on the database manager:
count(*)
in Oracle and PostgreSQL (possibly others as well, but I can't tell) it's detected as a "trivial" operation, the values are known to be irrelevant, so using the table index you can get the value without actually looping through the rows. With count(1) the behavior is similar (the result for each row is a constant that is not null), so it is not necessary to obtain the data to know if there are NULL values to discard.COUNT(*)
counts the records ofSELECT
the query keeping the query columns in memory, that is, if the query has 20 columns and 300 records, it will save the 6000 spaces in memory with its data. which would delay the processing of the query.COUNT(columna)
count records in which "column" is not NULLCOUNT(n)
(where n is a number) takes the value n (in this case) as a single column table where its value for each record is n for each record, no matter if it has 20 columns. for the example of the first case, it would be only 300 * 1 = 300 values, which would process the query faster.View Ref Toad World
COUNT(*)
count the records of the SELECT.COUNT(columna)
count records in which "column" is not NULL (column IS NOT NULL)COUNT(1)
(with a number) I have never used it. Microsoft help does not consider it ( link )I hope it serves you. Atte., Alex Eduardo Rivera Herrera.