I am working on an app in Rails using mysql with innodb. I have a need to fetch the full table count quite often and I understand that with innodb, counting all the records in a table can be quite expensive as it requires a full table scan. I'm looking at a typical table in the rails console and looking at the query times for counting the records. What I find so far is that the first time counting the records it takes a long time, but on subsequent tries it is much faster. For example:
2.2.2 :002 > Request.count
(683.7ms) SELECT COUNT(*) FROM `requests`
=> 260588
2.2.2 :003 > Request.count
(47.6ms) SELECT COUNT(*) FROM `requests`
=> 260588
2.2.2 :004 > Request.count
(46.7ms) SELECT COUNT(*) FROM `requests`
=> 260588
So, first off, do I even need to worry about optimizing this result? Perhaps the count is being cached by Rails or mySql or InnoDB and there's nothing to worry about.
I'm going to assume that there still is something to worry about in a production environment where multiple users are writing to the table at any given time. In that case, how do I 'reset' the caching or whatever is giving my an unrealistically sunny outlook on the count times so that I can do some honest benchmarking? I've tried writing to a record, or just reloading the console with reload!, but I never get the initial long time. I'll bet if I quit the console and restart mysql that would do it, but I'd rather not have to work that hard.
Finally, I've heard that a query like the following will run faster:
select count(*) from requests use index(<index_name>);
It seems like the most natural index to use is the id field.
select count(*) from service_requests use index(id)
But this gives me the following error:
ERROR 1176 (42000): Key 'id' doesn't exist in table 'requests'
But id is not just a key, it's the primary key. On some tables it's the only index. Why is id not considered a key?