A WordPress database that has grown far beyond the size of your actual content can be cleaned up safely, and kept lean on a schedule, with the optimizer built into the LiteSpeed Cache plugin (LSCWP). Most of the growth comes from revisions saved on every edit and from expired transients, which are temporary cached values that plugins store in wp_options and do not always delete. Abandoned drafts, spam comments and metadata orphaned by deleted posts add the rest, so a site that started at 50 MB can reach 2 GB a couple of years later. Measure the database first, take a backup, run the optimizer once by hand, then schedule it weekly so the bloat does not return.
How to verify
Before running any cleanup, measure the current state:
# Total database size
wp db size --tables
# Rows in key tables
wp db query "SELECT COUNT(*) as transients FROM wp_options WHERE option_name LIKE '_transient_%';"
wp db query "SELECT COUNT(*) as expired_transients FROM wp_options WHERE option_name LIKE '_transient_timeout_%' AND option_value < UNIX_TIMESTAMP();"
wp db query "SELECT COUNT(*) as revisions FROM wp_posts WHERE post_type = 'revision';"
wp db query "SELECT COUNT(*) as auto_drafts FROM wp_posts WHERE post_status = 'auto-draft';"
wp db query "SELECT COUNT(*) as trashed FROM wp_posts WHERE post_status = 'trash';"
wp db query "SELECT COUNT(*) as spam FROM wp_comments WHERE comment_approved = 'spam';"
wp db query "SELECT COUNT(*) as orphaned_postmeta FROM wp_postmeta WHERE post_id NOT IN (SELECT ID FROM wp_posts);"
# Overhead in each table (fragmented space that can be reclaimed)
wp db query "SELECT table_name, ROUND((data_free/1024/1024),2) AS free_MB FROM information_schema.tables WHERE table_schema = DATABASE() AND data_free > 0 ORDER BY data_free DESC;"
What’s happening
WordPress accumulates database rows in several well-known patterns.
Transients are short-lived key-value pairs stored in wp_options. Plugins use them to cache API responses, computed values, and lists. Most transients have a timeout, stored as a paired _transient_timeout_key row. When the timeout expires, WordPress is supposed to delete the transient on next access — but that cleanup only fires if something reads the transient. If the code that wrote the transient is uninstalled or stops running, the rows remain indefinitely. A busy WordPress site can accumulate tens of thousands of expired transient rows.
Post revisions are saved automatically by WordPress every time the editor auto-saves. WordPress defaults to keeping all revisions forever. A post edited 50 times has 49 revision rows in wp_posts, each with its own wp_postmeta rows. A site with 800 posts that have been heavily edited may have 15,000–30,000 revision rows.
Auto-drafts are saved when you open the block editor but do not publish. WordPress retains these as auto-draft status rows. Over time they pile up.
Orphaned post meta occurs when a post is deleted but the deletion code does not clean up wp_postmeta rows (this happens with improper bulk deletes, some import tools, and plugin bugs). The wp_postmeta table can grow to several times the size of wp_posts in badly maintained sites.
Table fragmentation occurs after many DELETE operations. MySQL/MariaDB does not immediately return deleted row space to the filesystem; instead it marks the space as free and reuses it for new rows. The data_free value in information_schema shows how much space is fragmented. OPTIMIZE TABLE compacts the table and returns fragmented space.
The procedure
Step 1 — Back up the database before running any cleanup.
# Create a timestamped backup
wp db export /home/user/db-backup-$(date +%Y%m%d-%H%M).sql
ls -lh /home/user/db-backup-*.sql
Never run database cleanup on a live site without a backup taken in the same session. LSCWP’s database optimizer is non-destructive in its defaults (it only removes rows with no referential value), but a backup is the prerequisite.
Step 2 — Configure database optimization settings in LSCWP.
Go to LiteSpeed Cache → DB Optimizer. Review each cleanup category:
-
Post Revisions: Set to remove. Optionally, set WordPress to retain only the last N revisions by adding to
wp-config.php:define('WP_POST_REVISIONS', 5);This limits future revision accumulation. LSCWP’s cleanup removes existing excess revisions.
-
Auto Drafts: Set to remove. These are safe to delete.
-
Trashed Posts: Set to remove posts and pages that have been in Trash for more than 30 days.
-
Expired Transients: Set to remove. This is the safest and often largest category.
-
All Transients: Leave off unless a plugin is misbehaving. Removing non-expired transients forces every plugin to regenerate its cache on next run, causing a temporary performance dip.
-
Spam and Trashed Comments: Set to remove.
-
Orphaned Post Meta: Set to remove. Verify your backup is current before enabling this — it is safe in most cases but irreversible without a restore.
-
Orphaned Relationship Data (term relationships with no post): Set to remove.
Step 3 — Run the optimizer manually for the first time.
Go to LiteSpeed Cache → DB Optimizer → Manage and click Optimize Now. LSCWP will display a before/after row count for each category. Review the output before confirming.
Alternatively, from WP-CLI:
wp litespeed-db clean revisions
wp litespeed-db clean auto_drafts
wp litespeed-db clean transient_expired
wp litespeed-db clean spam
wp litespeed-db clean trashed_posts
wp litespeed-db optimize-tables
Step 4 — Schedule recurring optimization.
Go to LiteSpeed Cache → DB Optimizer → Schedule. Set:
- Frequency: Weekly (Sunday at 03:00 is typical for a low-traffic window)
- Categories: Revisions, auto-drafts, expired transients, spam, trashed comments
- Leave orphaned meta on manual-only until you have confirmed no plugin depends on orphaned rows
Step 5 — Measure after cleanup.
# Database size after cleanup
wp db size --tables
# Confirm expired transients are gone
wp db query "SELECT COUNT(*) FROM wp_options WHERE option_name LIKE '_transient_timeout_%' AND option_value < UNIX_TIMESTAMP();"
# Confirm revisions are reduced
wp db query "SELECT COUNT(*) FROM wp_posts WHERE post_type = 'revision';"
After the first full cleanup, a heavily bloated site typically drops 30–70% in database size. Subsequent weekly runs keep the size stable.
Common pitfalls
Removing all transients breaks a plugin. Some plugins store long-lived transients that are not marked with a timeout (or are set with a very long timeout). Removing them forces the plugin to regenerate expensive data on next request. If a cleanup breaks something, check which plugins write to wp_options with the transient prefix and exclude their keys from cleanup.
Revisions deleted but wp-config.php still allows unlimited revisions. LSCWP cleanup removes existing excess revisions but does not set the WP_POST_REVISIONS constant. Without that constant, WordPress will accumulate new revisions at the same rate. Always pair the cleanup with the constant to prevent recurrence.
OPTIMIZE TABLE locking tables on large databases. MySQL’s OPTIMIZE TABLE acquires a write lock on InnoDB tables (it uses ALTER TABLE ... ENGINE=InnoDB internally on InnoDB). On tables larger than 500 MB, this lock can last several seconds and block WordPress reads. Run OPTIMIZE TABLE during a maintenance window, or use Percona’s pt-online-schema-change for zero-downtime optimization on very large tables.
Orphaned meta removal deleting data a plugin considers valid. Some plugins write wp_postmeta rows with a post_id that references a non-existent post intentionally (using 0 or a placeholder ID as a global settings store). Removing these breaks the plugin. Before enabling orphaned meta cleanup, query the specific rows that would be deleted:
wp db query "SELECT meta_key, COUNT(*) FROM wp_postmeta WHERE post_id NOT IN (SELECT ID FROM wp_posts) GROUP BY meta_key ORDER BY COUNT(*) DESC LIMIT 20;"
Review the meta keys. If any belong to an active plugin, exclude that plugin’s meta keys from cleanup.
Scheduling cleanup during business hours. Even lightweight database operations create brief lock contention. Schedule optimization for the lowest-traffic window, typically between 02:00 and 05:00 in the site’s primary timezone.
Database maintenance is an ongoing operational task, not a one-time fix. Stack Harbor includes scheduled database optimization in standard managed operations coverage, with before/after size verification and alert thresholds for abnormal growth.