Slow COUNT(*) Query in MySQL with Where Clause
When dealing with sluggish MySQL queries involving COUNT(*), understanding the underlying factors is paramount. In this particular case, the long execution time is not immediately apparent from the query itself or the EXPLAIN statement.
Understanding the Issue
The table in question, change_event, has a clustered primary key on the change_event_id column. In InnoDB, clustered primary keys are stored alongside the data in the data pages, unlike non-clustered indexes that reside in separate index pages.
The Problem of Range Scans on Clustered Primary Keys
The presented query performs a range scan on the clustered primary key, where it needs to scan a significant portion of the table. This can be time-consuming since the data pages may not be physically stored in sorted order, resulting in extra I/O operations.
Potential Solutions
To optimize this query, consider implementing one or both of the following strategies:
Additional Note:
Consider modifying the change_event_id column to be BIGINT UNSIGNED if it is indeed an auto-incrementing column starting from zero. This would prevent potential issues with signed integer overflow.
The above is the detailed content of Why is My COUNT(*) Query with a WHERE Clause Slow in MySQL?. For more information, please follow other related articles on the PHP Chinese website!