Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

count

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; 
like image 418
bread Avatar asked Jun 09 '10 06:06

bread


People also ask

Which is faster count (*) or count column?

The simple answer is no – there is no difference at all. The COUNT(*) function counts the total rows in the table, including the NULL values.

Is Count ID faster than count *?

Your use of COUNT(*) or COUNT(column) should be based on the desired output only. ... if you have a non-nullable column such as ID, then count(ID) will significantly improve performance over count(*). The two seem to contradict each other.

What is difference between count (*) and count column in Oracle?

for all purposes count(*) and count(1) are the same, you should use count(*) though.... count (col) only counts the not null entries in the table. That's incorrect, count(*) counts all rows, no matter of null values.

What is the difference between count (*) and count attribute?

The difference is simple: COUNT(*) counts the number of rows produced by the query, whereas COUNT(1) counts the number of 1 values.


1 Answers

  • COUNT(*) counts all rows
  • COUNT(column) counts non-NULLs only
  • COUNT(1) is the same as COUNT(*) because 1 is a non-null expressions

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

like image 113
gbn Avatar answered Oct 12 '22 11:10

gbn