Skip to main content
Documents
Clauses StatementsKeywordsExpressionsFunctionsIndexesPerformance Optimization

MySQL Query Cache Performance Optimization

The MySQL Query Cache is a performance optimization feature that stores the result set of a query, allowing identical queries to be served directly from the cache. This reduces the need for repeated query execution, thereby saving processing time and enhancing performance.

Usage

The Query Cache is particularly useful in read-heavy environments where the same query is executed multiple times. It is enabled and configured through MySQL server settings. Note that the Query Cache is deprecated as of MySQL 5.7.20 and removed in MySQL 8.0. Consider alternative caching solutions for newer versions.

Syntax

SET GLOBAL query_cache_size = value;
SET GLOBAL query_cache_type = type;
  • query_cache_size specifies the amount of memory allocated for the cache.
  • query_cache_type defines how the cache is used (0 for off, 1 for on, and 2 for demand).

Examples

1. Enable Query Cache

SET GLOBAL query_cache_size = 1048576;
SET GLOBAL query_cache_type = 1;

This example enables the Query Cache with a size of 1MB and sets it to cache all queries.

2. Cache Specific Queries

SET GLOBAL query_cache_type = 2;

This setting configures the Query Cache to cache only queries that explicitly request it via SELECT SQL_CACHE.

3. Using SQL_CACHE Hint

SELECT SQL_CACHE * FROM products WHERE category = 'electronics';

Here, SQL_CACHE explicitly instructs MySQL to cache the result of this specific query, useful when query cache type is set to demand.

Tips and Best Practices

  • Use in read-heavy environments. The Query Cache is most beneficial where queries outnumber updates, but it is not effective for frequently updated data, as each update invalidates the cache.
  • Monitor cache usage. Regularly check cache hit rates and size to ensure optimal configuration. Use commands like SHOW STATUS LIKE 'Qcache%' to assess cache performance.
  • Invalidate on table updates. Be aware that any update to a table invalidates relevant cached queries.
  • Limit cache size. Avoid setting an excessively large cache size, as it can lead to overhead and inefficiency.
  • Performance impact. Be mindful of performance impacts due to mutex contention in highly concurrent environments.
  • Consider alternative caching solutions. For high scalability and compatibility with newer MySQL versions, consider application-level caching solutions like Memcached or Redis.
  • Utilize monitoring tools. Use the Performance Schema or other monitoring tools for better insights into cache performance and to aid in decision-making regarding caching strategies.

SQL Upskilling for Beginners

Gain the SQL skills to interact with and query your data.
Start Learning for Free