count(*) vs count(column-name) - which is more correct?

SqlCount

Sql Problem Overview


Does it make a difference if you do count(*) vs count(column-name) as in these two examples?

I have a tendency to always write count(*) because it seems to fit better in my mind with the notion of it being an aggregate function, if that makes sense.

But I'm not sure if it's technically best as I tend to see example code written without the * more often than not.

count(*):

select customerid, count(*), sum(price) 
from items_ordered
group by customerid
having count(*) > 1;

vs. count(column-name):

SELECT customerid, count(customerid), sum(price)
FROM items_ordered
GROUP BY customerid
HAVING count(customerid) > 1;

Sql Solutions


Solution 1 - Sql

Your use of COUNT(*) or COUNT(column) should be based on the desired output only.

Solution 2 - Sql

This applies to MySQL. I'm not sure about the others.

The difference is:

  • COUNT(*) will count the number of records.
  • COUNT(column_name) will count the number of records where column_name is not null.

Therefore COUNT(*) is what you should use. If you're using MyISAM and there is no WHERE clause, then the optimiser doesn't even have to look at the table, since the number of rows is already cached.

Solution 3 - Sql

When it's an identifier (and guaranteed to be non-NULL) then it probably doesn't matter.

However, there is a difference between COUNT(*) and COUNT(column) in general, in that COUNT(column) will return a count of the non-NULL values in the column. There is also the COUNT(DISTINCT column) variant which returns the number of unique, non-NULL values.

Solution 4 - Sql

Yes, there is possible difference in performance. Depending on your query, and the indexing of the table in question, it can be quicker to get the count from the index instead of going to table for the data. Thus you probably should specify the field name, instead of using *.

Solution 5 - Sql

Generally it's the same, but in details AFAIK "count(*)" is better b/c "count(columnname)" forces DB to execute a little more code to lookup that column name (but not necessary though).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbreadView Question on Stackoverflow
Solution 1 - SqlgbnView Answer on Stackoverflow
Solution 2 - SqlnickfView Answer on Stackoverflow
Solution 3 - SqlDean HardingView Answer on Stackoverflow
Solution 4 - SqlTommiView Answer on Stackoverflow
Solution 5 - Sqlzed_0xffView Answer on Stackoverflow