Use EXPLAIN to find and fix slow MySQL queries
Slow database queries are one of the main reasons of a slow WordPress site. MySQL’s EXPLAIN shows how the server is going to run a SELECT: which index it uses, how many rows it expects to read, and whether it is about to scan the whole table. Reading its output takes ten minutes to learn and saves hours of guessing.
Problem: A query is slow, and you need to find out why and which index would help, without guessing.
Solution: Put EXPLAIN in front of the query in phpMyAdmin or the MySQL console, read the type, key, rows and Extra columns, and add an index where a full scan happens.
Run EXPLAIN
The examples use the standard wp_ prefix; use the one from your wp-config.php.
EXPLAIN SELECT ID, post_title FROM wp_posts WHERE post_status = 'publish' AND post_type = 'post' ORDER BY post_date DESC LIMIT 10;
Read the output
- type: how the table is read.
ALLis a full table scan,indexa full index scan;range,ref,eq_refandconstmean an index is used efficiently. - key: the index MySQL chose (
NULL= none). possible_keys lists the candidates. - rows: how many rows MySQL expects to examine. Compare it with the number you actually get back.
- Extra: warnings.
Using filesortandUsing temporarymean extra sorting or a temporary table;Using indexis good, the query is answered from the index alone.
For the query above WordPress already has the index type_status_date (post_type, post_status, post_date, ID), so you will see ref and a small rows.
A typical problem: meta queries
Searching by a meta value is where WordPress queries usually get slow. The postmeta table has an index on meta_key, but not on meta_value:
EXPLAIN SELECT post_id FROM wp_postmeta WHERE meta_key = 'event_date' AND meta_value >= '20210101';
If rows is close to the number of all rows with this key, and the table has hundreds of thousands of them, an index on the key and the first characters of the value helps (meta_value is a LONGTEXT, so only a prefix can be indexed):
ALTER TABLE wp_postmeta ADD INDEX meta_key_value ( meta_key(191), meta_value(32) );
Run the same EXPLAIN again: key should now show the new index and rows should drop.
EXPLAIN ANALYZE
In MySQL 8.0.18+ EXPLAIN ANALYZE actually runs the query and shows the real time and the real row counts next to the estimates. A big difference between them means the table statistics are outdated; ANALYZE TABLE wp_postmeta; refreshes them.
NOTE: An index speeds up reads but slows down every INSERT, UPDATE and DELETE a little, because MySQL has to maintain it. Index only the columns you really filter or sort by. On a big live table, add the index when the site has few visitors: depending on the MySQL version and the table size, ALTER TABLE can lock writes for a while.