views:

795

answers:

5

Is there a difference between the following queries, assuming there is a primary field 'id' in the table (as in speed, etc)?

SELECT COUNT(id) 
  FROM table

vs.

SELECT COUNT(*) 
  FROM table
+3  A: 

Not in MySQL, no, it has optimized the COUNT well (assuming that your id field is already a PK --which is fairly self-describing). But in for example PostgreSQL the COUNT(pkcolumnname) is much faster.

BalusC
+4  A: 

Have a look at Count(*) vs Count(col) at www.mysqlperformanceblog.com, they discuss this topic for various 'col' types (NOT NULL or not, with index, etc) and this for MyISAM and InnoDB tables.

Pascal Thivent
A: 

I know the question is about MySQL, but for what it's worth, count(*) is recommended for Oracle: which goes to show that this is database specific (see comment above from BalusC). Since a lot of databases (MS-SQL, MySQL) have information schema tables that hold various types of metadata, there are bound to be differences if one syntax is simply looking up a readily-available value, and another is going straight to the table. At the end of day: try different options, an see what EXPLAIN is telling you is going on behind the scenes.

davek
A: 

The difference depends on how count() is implemented in your database engine. For naive approaches, select count(*) will build a result set containing every column from every row in the result set, count those, and return the result. In such a case, using count(id) will reduce this memory and performance overhead to retrieving a single, small column instead of a structure the width of the source table(s).

An optimized approach such as that used by MS SQL will recognize the count() construct and just count the rows without building an intermediate result buffer, so count() is roughly equivalent to count(id).

David Lively