MySQL's query cache handles the issue of sending the same query over and over to MySQL. If the query cache is enabled, the result of a query is stored, along with the original query string. For subsequent queries, the server first checks if that exact query has been issued before. If so, the result is simply returned from the query cache, saving all the time of parsing, optimization and execution.
To use the query cache effectively, consider:
- The query strings must be absolutely identical to use the cache. Whitespace and case sensitivity matter.
- Non-deterministic queries (those that can return different results each time they are run) cannot be cached. For this reason, replace non-deterministic functions with constant data wherever possible. For
WHERE field < CURRENT_DATE()
WHERE field < '2007-07-12'
The latter version might need to be evaluated only once per day.
- You can configure the server to cache all queries except those marked, or to only cache those queries which are explicitly marked. Use the first if you have mostly static data and deterministic queries. Use the second if you have mostly volatile data or non-deterministic queries.
- If the tables involved in a query are changed (data added or deleted), the relevant queries will be pruned from the cache. Space in the cache is limited, so do not allow queries against highly volatile tables to cache.
For more information about the query cache in MySQL, check out the MySQL developer site.
This was first published in July 2007