Optimization for Slow "SELECT COUNT(*)" Query in MySQL
When querying large tables, slow performance can arise despite the presence of a WHERE clause. Let's analyze a specific case where a "SELECT COUNT(*)" query with a range criterion takes an excessive amount of time.
The explanation provided by "EXPLAIN" suggests a range scan is occurring. However, the performance discrepancy between the full count and the filtered count remains unexplained.
Upon examining the table definition, we observe that the "change_event_id" column serves as the primary key, which is stored in clustered form. This means that the primary key values are stored together with the data on the same disk pages. As a result, range scans on the primary key require reading through all the data pages.
To improve performance, consider the following strategies:
Furthermore, it is recommended to modify the "change_event_id" column to be "bigint unsigned" if it is incrementing from zero. This will ensure that it can store larger values without overflowing.
By implementing these optimizations, the performance of the "SELECT COUNT(*)" query with the range criterion should significantly improve, making it comparable to the full count.
The above is the detailed content of How to Optimize a Slow \"SELECT COUNT(*)\" Query Involving a Range Scan on the Primary Key in MySQL?. For more information, please follow other related articles on the PHP Chinese website!