Query Cache Configuration for MySQL Databases
Background
The query cache stores the text of a SELECT statement together with the corresponding result sent to the client.
Application Scenarios
Query cache is used in scenarios where the same statement is submitted frequently while data is seldom changed in tables, for example, some static pages or information that is not changed frequently on a page.
The query cache needs to cache the latest data results. Therefore, when the table data is changed (insert, update, delete, or other operations that may cause data changes), the query cache is refreshed. In a scenario where the update frequency is very low while the read-only query frequency is very high, enabling the query cache is a good choice.
Unsupported Scenarios
The query cache requires that two SQL requests must be the same, including SQL statements, connected databases, protocol versions, and character sets. Do not use the query cache in the following scenarios:
- Subqueries
- SQL statements that are invoked by procedures, functions, triggers, and events, or references to these results
- Queries that use the following special functions: BENCHMARK(), CURDATE(), CURRENT_TIME(), CURRENT_TIMESTAMP(), NOW(), SLEEP(), CONNECTION_ID(), CURRENT_DATE(), CURRENT_USER(), PASSWORD(), RAND(), UUID(), ENCRYPT(), and LAST_INSERT_ID()
- Queries involved in mysql, information_schema, or performance_schema
- Statements similar to SELECT ... LOCK IN SHARE MODE, SELECT ... FOR UPDATE, SELECT ... INTO OUTFILE, SELECT ... INTO DUMPFILE, and SELECT * FROM ... WHERE autoincrement_col IS NULL
- SELECT execution plans that use temporary tables
- Queries with no table referenced, such as SELECT 1+2
- Queries that generate alarms (warning)
- SELECT statements that contain the keyword SQL_NO_CACHE
- Queries involved in table partitioning
There are many constraints on using the query cache. You are advised to enable the query cache only when data is frequently read but rarely updated. For details on how to enable the query cache, see Enabling Query Cache.
Enabling Query Cache
Set query_cache_type to 1 and query_cache_size to 67108864.
You can set query_cache_size to a value less than 100 MB. The value 67108864 is used as an example. In MySQL databases, the query cache is controlled by a global lock. Each time the data is updated, the memory block of the query cache needs to be locked.
Disabling Query Cache
Set query_cache_type to 0 and query_cache_size to 0.
Did this article solve your problem?
Thank you for your score!Your feedback would help us improve the website.