Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQL, what’s the difference between count(*) and count('x')? [duplicate]

Tags:

sql

I have the following code:

SELECT <column>, count(*)
FROM <table>
GROUP BY <column> HAVING COUNT(*) > 1;

Is there any difference to the results or performance if I replace the COUNT(*) with COUNT('x')?

(This question is related to a previous one)

like image 998
Andrew Avatar asked Sep 12 '08 15:09

Andrew


1 Answers

To say that SELECT COUNT(*) vs COUNT(1) results in your DBMS returning "columns" is pure bunk. That may have been the case long, long ago but any self-respecting query optimizer will choose some fast method to count the rows in the table - there is NO performance difference between SELECT COUNT(*), COUNT(1), COUNT('this is a silly conversation')

Moreover, SELECT(1) vs SELECT(*) will NOT have any difference in INDEX usage -- most DBMS will actually optimize SELECT( n ) into SELECT(*) anyway. See the ASK TOM: Oracle has been optimizing SELECT(n) into SELECT(*) for the better part of a decade, if not longer: http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1156151916789

problem is in count(col) to count() conversion **03/23/00 05:46 pm *** one workaround is to set event 10122 to turn off count(col) ->count() optimization. Another work around is to change the count(col) to count(), it means the same, when the col has a NOT NULL constraint. The bug number is 1215372.

One thing to note - if you are using COUNT(col) (don't!) and col is marked NULL, then it will actually have to count the number of occurrences in the table (either via index scan, histogram, etc. if they exist, or a full table scan otherwise).

Bottom line: if what you want is the count of rows in a table, use COUNT(*)

like image 186
Matt Rogish Avatar answered Sep 22 '22 22:09

Matt Rogish