5

Possible Duplicate:
COUNT(id) vs. COUNT(*) in MySQL

Short but simple: in MySQL, would a SELECT COUNT(fld) AS count FROM tbl be faster than SELECT COUNT(*) AS count FROM tbl as I understand * is the "all" selector in MySQL.

Does COUNT(*) select all rows to compute a count, and therefore make a query like SELECT(id) less expensive? Or does it not really matter?

Community
  • 1
  • 1
Martin Bean
  • 38,379
  • 25
  • 128
  • 201

3 Answers3

7

No, count(*) is faster than count(fld) (in the cases where there is a difference at all).

The count(fld) has to consider the data in the field, as it counts all non-null values.

The count(*) only counts the number of records, so it doesn't need access to the data.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
2
SELECT COUNT(*) AS count FROM tbl

The above query doesn't even count the rows assuming there's no WHERE clause, it reads directly from the table cache. Specifying a field instead of * forces SQL to actually count the rows, so it's much faster to use * when there's no WHERE clause.

Ben
  • 60,438
  • 111
  • 314
  • 488
1

* is the β€œall” selector in MySQL

That's true when you SELECT columns, where the * is a shortcut for the whole column list.

SELECT * becomes SELECT foo, bar.

But COUNT(*) is not expanded to COUNT(foo,bar) which is nonsensical in SQL. COUNT is an aggregate function which normally needs one value per selected row.

Benoit
  • 76,634
  • 23
  • 210
  • 236