Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - Complexity of: SELECT COUNT(*) FROM MyTable;

What is the complexity of this MySQL query

SELECT COUNT(*) FROM MyTable;

Is the count of number of entries in a table stored somewhere and updated every time a row is inserted or deleted? If that is the case, then the complexity should be O(1).

like image 766
manish_s Avatar asked Mar 10 '11 09:03

manish_s


People also ask

What is the complexity of count (*) query?

The previous also means that other queries, such as count queries like COUNT(*) FROM TABLE; will have a time complexity of O(n), because a full table scan will be required unless the total row count is stored for the table.

Which is faster count (*) or count column?

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.

Which is faster count (*) or Count 1?

MySQL: Doesn't matter. Sometimes COUNT(1) was faster, sometimes COUNT(*) was faster, so all differences were only benchmark artifacts. Oracle: Doesn't matter. Like MySQL.

What does SELECT count (*) from table do?

The COUNT (*) function returns the number of rows that satisfy the WHERE clause of a SELECT statement.


2 Answers

It depends on the storage engine.

  • For MyISAM the total row count is stored for each table so SELECT COUNT(*) FROM yourtable is an operation O(1). It just needs to read this value.
  • For InnoDB the total row count is not stored so a full scan is required. This is an O(n) operation.

From the manual:

InnoDB does not keep an internal count of rows in a table. (In practice, this would be somewhat complicated due to multi-versioning.) To process a SELECT COUNT(*) FROM t statement, InnoDB must scan an index of the table, which takes some time if the index is not entirely in the buffer pool. If your table does not change often, using the MySQL query cache is a good solution. To get a fast count, you have to use a counter table you create yourself and let your application update it according to the inserts and deletes it does. SHOW TABLE STATUS also can be used if an approximate row count is sufficient. See Section 13.2.13.1, "InnoDB Performance Tuning Tips".

like image 52
Mark Byers Avatar answered Sep 21 '22 22:09

Mark Byers


AFAIK in MyISAM rows-count are cached, in InnoDB not, and with every count-all he counts all rows.

like image 23
cichy Avatar answered Sep 19 '22 22:09

cichy