Clean up WordPress database bloat by removing orphaned postmeta and revisions

Clean up WordPress database bloat

After a few years a WordPress database carries thousands of revisions, expired transients, spam comments and meta rows of posts that no longer exist. Backups grow, and queries on wp_options and wp_postmeta slow down. The cleanup is safe if you measure first, delete by category, and use WP-CLI where it exists, because WP-CLI goes through WordPress and also removes the related rows.

Problem: The database has grown to several gigabytes, and it is not clear which part is real content and which is leftovers.

Solution: Measure the table sizes and count each kind of leftover with SQL, make a backup, delete revisions, spam and expired transients with WP-CLI, remove orphaned meta with targeted DELETE queries, and rebuild only the tables that lost a lot of rows.

The examples use the wp_ prefix; replace it with yours.

Measure

SELECT table_name, ROUND((data_length + index_length) / 1024 / 1024) AS mb
FROM information_schema.tables
WHERE table_schema = DATABASE()
ORDER BY mb DESC
LIMIT 10;

SELECT COUNT(*) FROM wp_posts WHERE post_type = 'revision';
SELECT comment_approved, COUNT(*) FROM wp_comments GROUP BY comment_approved;   -- spam, trash, 0, 1
SELECT COUNT(*) FROM wp_postmeta pm
WHERE NOT EXISTS (SELECT 1 FROM wp_posts p WHERE p.ID = pm.post_id);
SELECT COUNT(*) FROM wp_options
WHERE option_name LIKE '\_transient\_timeout\_%' AND option_value < UNIX_TIMESTAMP();

The _ in LIKE is a wildcard for one character, so it is escaped with a backslash to match the real underscore.

Back up

wp db export before-cleanup.sql

Delete with WP-CLI

wp post delete $(wp post list --post_type=revision --format=ids) --force
wp comment delete $(wp comment list --status=spam --format=ids) --force
wp comment delete $(wp comment list --status=trash --format=ids) --force
wp transient delete --expired

wp post delete also removes the meta and term relationships of each revision. On a site with tens of thousands of revisions, run it in parts, for example with --posts_per_page=500 in the wp post list call, repeated until nothing is left. To keep revisions from piling up again, limit them in wp-config.php; see control post revisions.

Orphaned meta with SQL

DELETE pm FROM wp_postmeta pm
LEFT JOIN wp_posts p ON p.ID = pm.post_id
WHERE p.ID IS NULL;

DELETE cm FROM wp_commentmeta cm
LEFT JOIN wp_comments c ON c.comment_ID = cm.comment_id
WHERE c.comment_ID IS NULL;

The same queries as a reusable procedure: MySQL stored procedures for a cleanup routine.

Reclaim the space

OPTIMIZE TABLE wp_posts, wp_postmeta, wp_comments;

On InnoDB, OPTIMIZE TABLE rebuilds the table and gives the free space back to the disk. It is only worth it after deleting a large share of the rows, and it locks the table briefly, so run it at a quiet time.

Run it regularly

# crontab of the site user: every Sunday night
30 3 * * 0 wp --path=/var/www/example --quiet transient delete --expired
45 3 * * 0 wp --path=/var/www/example --quiet comment delete $(wp --path=/var/www/example comment list --status=spam --format=ids) --force

Expired transients and spam come back every week, so they belong in a scheduled job; revisions are better limited at the source than deleted by cron. How to set up the crontab: Linux cron jobs for WordPress maintenance.

NOTE: The biggest win is often not in the deleted rows but in wp_options: large autoloaded options of removed plugins are read on every request. Check them with SELECT option_name, LENGTH(option_value) FROM wp_options WHERE autoload = 'yes' ORDER BY 2 DESC LIMIT 20; and see wp_options autoload.