Optimize WordPress Database Tables with ANALYZE, OPTIMIZE, and Slow Query Log

Optimize WordPress database tables: cleanup, ANALYZE and OPTIMIZE

Over the years a WordPress database collects revisions, expired transients, trashed posts and orphaned meta rows, and the large tables (wp_posts, wp_postmeta, wp_options) get fragmented. The MySQL optimizer also works with index statistics that can be outdated after big imports or deletions. Three commands help: ANALYZE TABLE refreshes the index statistics, OPTIMIZE TABLE rebuilds a table and returns free space, and CHECK TABLE checks a table for errors without changing it.

Problem: A database that has been running for years gets slower even though the indexes are fine: it is full of leftovers, and the optimizer chooses bad plans.

Solution: Delete the leftovers with targeted SQL, refresh the statistics with ANALYZE TABLE, and rebuild only the tables with a lot of free space with OPTIMIZE TABLE. Make a backup first: the deletions cannot be undone.

The examples use the standard wp_ prefix; use the one from your wp-config.php.

1. Measure

SELECT TABLE_NAME,
       ROUND( DATA_LENGTH / 1024 / 1024, 1 ) AS data_mb,
       ROUND( INDEX_LENGTH / 1024 / 1024, 1 ) AS index_mb,
       ROUND( DATA_FREE / 1024 / 1024, 1 ) AS free_mb,
       TABLE_ROWS
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'helloadmin' -- your database name
ORDER BY DATA_LENGTH + INDEX_LENGTH DESC;

SELECT post_type, post_status, COUNT(*) FROM wp_posts GROUP BY post_type, post_status ORDER BY 3 DESC;

The second query shows how much of wp_posts is revisions, auto-drafts and trash.

2. Clean up

-- Revisions (or limit them in the future with WP_POST_REVISIONS in wp-config.php)
DELETE FROM wp_posts WHERE post_type = 'revision';

-- Auto-drafts older than a week
DELETE FROM wp_posts WHERE post_status = 'auto-draft' AND post_date < NOW() - INTERVAL 7 DAY;

-- Meta rows of posts that no longer exist
DELETE pm FROM wp_postmeta pm
LEFT JOIN wp_posts p ON p.ID = pm.post_id
WHERE p.ID IS NULL;

-- Expired transients: the timeout rows and their values
DELETE t, v FROM wp_options t
JOIN wp_options v ON v.option_name = CONCAT( '_transient_', SUBSTRING( t.option_name, 20 ) )
WHERE t.option_name LIKE '\_transient\_timeout\_%' AND t.option_value < UNIX_TIMESTAMP();

Deleting revisions with SQL leaves their term relationships behind; they are harmless, but wp post delete $(wp post list --post_type=revision --format=ids) --force in WP-CLI deletes revisions the WordPress way, with everything attached. WordPress itself deletes expired transients once a day and empties the trash after 30 days, so the transients query is mostly needed when WP-Cron does not run.

3. ANALYZE

ANALYZE TABLE wp_posts, wp_postmeta, wp_options, wp_comments, wp_commentmeta,
              wp_terms, wp_term_taxonomy, wp_term_relationships, wp_users, wp_usermeta;

For InnoDB it reads a sample of index pages and updates the cardinality estimates. It is fast and does not block the site. Run it after big deletions and imports.

4. OPTIMIZE, only where it pays

OPTIMIZE TABLE wp_postmeta;
OPTIMIZE TABLE wp_options;

For InnoDB, OPTIMIZE TABLE is the same as ALTER TABLE … ENGINE=InnoDB: the table is rebuilt, the free space returns to the file system, and the statistics are updated. MySQL prints “Table does not support optimize, doing recreate + analyze instead”, which is normal. Since MySQL 5.6 the rebuild is mostly online, but it needs free disk space about the size of the table, and on very large tables it takes a while, so run it when traffic is low. It pays off when free_mb from step 1 is a large share of the table, typically after the cleanup.

NOTE: Cleanup and ANALYZE fix the symptoms; to find the queries that are actually slow, use the slow query log, and then EXPLAIN for each of them.