WordPress Database Cleanup: Tables That Grow Without You

A WordPress database rarely fails because one table exploded. It gets heavy because six tables grew quietly: options from every plugin you have ever installed, postmeta from every field, revisions from every save, and WooCommerce’s own order, session, and job tables.

The dashboard does not show any of that. The site still loads, the admin still works, and the only signal is a backup that takes longer or a host warning about disk usage.

WordPress database cleanup is the work of finding which of those tables is actually large, deciding whether its rows still do something, and removing only the part that does not. The order matters more than the SQL.

What actually grows

Start with the tables that accumulate by design. A default install has twelve tables; a store with a page builder, an SEO plugin, a form plugin, and a backup plugin can have forty.

TableWhat lands thereWhy it grows
wp_optionsPlugin settings, transients, cron entriesEvery plugin activation adds rows; transients expire but are not always deleted
wp_postmetaCustom fields, builder data, SEO fieldsOne row per field per post, plus rows left behind by deleted posts
wp_postsPosts, pages, revisions, drafts, trashed itemsRevisions are full copies of the post
wp_woocommerce_sessionsOne row per visitor sessionTraffic, not catalog size, drives it
wp_actionscheduler_actionsBackground jobs and their historyEvery order email, subscription renewal, and sync job
wp_wc_orders and friendsOrders, addresses, order metaHPOS stores order data outside wp_posts

Two entries in that table deserve a closer look. Revisions are not “old versions” that WordPress deletes on its own; with WP_POST_REVISIONS left at its default of true, the limit is unlimited. And wp_options is not just settings: it is also where transients live, which makes it the table most likely to hold data nobody remembers creating.

The WordPress optimization handbook lists autoloaded options as a first-order performance concern for the same reason: the table is read on every request, not only when an admin page opens.

Measure before you delete anything

The first query is table size. Run it in phpMyAdmin, Adminer, or wp db query; replace wp_ with your prefix if it differs.

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 = DATABASE()
ORDER BY data_length + index_length DESC
LIMIT 20;

data_free is space the table has reserved but is not using. It matters after a large delete: the rows are gone, the file is still the same size, and the next backup still copies the file. table_rows is an estimate on InnoDB, so treat it as a ranking signal rather than a count.

WP-CLI gives you the same picture without opening a database client:

wp db size --tables --human-readable

The wp db size command reports the total when you leave off --tables, and that total is the number to compare month over month. A database that grows 2 MB a month is behaving. One that grows 200 MB a month has a source, and it is usually in one of the sections below.

Autoloaded options: the rows on every request

wp_load_alloptions() reads every option marked for autoload and keeps the result in memory for the request. That is intentional: it saves a query for settings that are needed everywhere.

The problem is what gets marked for autoload. A page builder stores its license and module list, an SEO plugin stores its titles and social defaults, and a caching plugin may store its entire configuration. None of those are large on their own. Together, they are read on every front-end request, including the ones that only need a post.

Since WordPress 6.6, the autoload column accepts more than yes and no: the values considered for autoloading are yes, on, auto-on, and auto. The autoload values reference documents the list, and it matters when you audit an older database where every row says yes.

Measure the total:

SELECT COUNT(*) AS autoloaded_options,
       ROUND(SUM(LENGTH(option_value)) / 1024, 1) AS size_kb
FROM wp_options
WHERE autoload IN ('yes', 'on', 'auto-on', 'auto');

Site Health runs the same calculation. If the total passes 800,000 bytes, it reports that autoloaded options could slow the site. That threshold is filterable with site_status_autoloaded_options_size_limit, but the default is a reasonable line: 800 KB of configuration read on every request is a lot.

Find the largest rows:

SELECT option_name,
       LENGTH(option_value) AS bytes,
       autoload
FROM wp_options
WHERE autoload IN ('yes', 'on', 'auto-on', 'auto')
ORDER BY bytes DESC
LIMIT 25;

Do not delete an option because its name looks unfamiliar. A safer first pass is to turn autoload off for a large option that is only needed in the admin, then confirm the plugin still works:

UPDATE wp_options
SET autoload = 'no'
WHERE option_name = 'example_plugin_cache_settings';

That keeps the data and removes it from the per-request load. WP-CLI’s wp option update has an --autoload=off flag, but it expects the value as well, so the SQL above is clearer when the value should not change.

Transients are the hidden half of wp_options

A transient is a cached value with an expiry date. Plugins use them for API responses, feed imports, dashboard widgets, and remote update checks. Core stores them in wp_options under _transient_ and _transient_timeout_ keys, as the Transients API explains.

Expired transients are deleted when something tries to read them. The ones nobody reads again can stay in the table indefinitely. That is how a site ends up with tens of thousands of _transient_ rows and no plugin that admits to creating them. On a site with a persistent object cache, transients live in Redis or Memcached instead, so the options table stays small and the cache backend becomes the thing to measure.

WP-CLI has a targeted cleanup:

wp transient delete --expired

Run that before the broader options audit. Do not run wp transient delete --all on a live site during traffic: it clears valid caches too, and every one of them will be rebuilt at once.

Revisions: full copies, no limit by default

Every save of a post can create a revision. A revision is a row in wp_posts with post_type = 'revision', plus the meta that goes with it. A 3,000-word post edited thirty times is thirty copies of the content, and the revisions are included in every backup.

Count them by parent:

SELECT post_parent,
       COUNT(*) AS revisions
FROM wp_posts
WHERE post_type = 'revision'
GROUP BY post_parent
ORDER BY revisions DESC
LIMIT 20;

If the top post has 200 revisions, the fix is two-part. Cap future revisions in wp-config.php:

define( 'WP_POST_REVISIONS', 10 );

Then remove the excess on staging first:

wp post list --post_type=revision --format=count
wp post list --post_type=revision --format=ids | xargs -n 100 wp post delete --force

If the count is zero, stop there. With no input, xargs still runs wp post delete --force once, and WP-CLI errors on the missing IDs. Otherwise the batch size of 100 keeps a single call from timing out on thousands of IDs. Test it on a copy, confirm the post still renders, and only then run it on production. A revision is a real post row; deleting it also removes its meta, which is what you want, but it is not a change to make without a backup.

WP_POST_REVISIONS accepts true (unlimited), false (off), or a number. Ten is a reasonable ceiling for editorial sites. A store product that changes price weekly does not need thirty historical copies of the description.

Orphaned postmeta: rows with no post

WordPress does not use foreign keys between wp_posts and wp_postmeta. When a post is deleted, core deletes its meta through the API, but a plugin that writes directly to the table, a failed import, or a duplicated site can leave rows behind.

Count them:

SELECT COUNT(*) AS orphaned_rows
FROM wp_postmeta pm
LEFT JOIN wp_posts p ON p.ID = pm.post_id
WHERE p.ID IS NULL;

If the number is small, leave it alone. If it is tens of thousands, remove it during a maintenance window, after a backup:

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

This is a multi-table delete, so it takes a lock proportional to the rows it touches. On a large table, run it when traffic is low. There is no undo, and a backup is the only rollback that matters here.

One exception is worth checking before you delete: some plugins store shared data in wp_postmeta with post_id = 0. That is unusual and generally a bug, but if a plugin’s documentation says it uses the table that way, exclude those rows and fix the plugin instead.

WooCommerce tables need a different kind of cleanup

A store’s database is not just a bigger blog database. WooCommerce adds tables that grow with orders and traffic, and the right action for each one is different.

Orders and HPOS

Since WooCommerce 8.2, new installations store orders in four custom tables by default: wp_wc_orders, wp_wc_order_addresses, wp_wc_order_operational_data, and wp_wc_orders_meta. The HPOS documentation explains the split and the migration path for older stores.

Those tables are the business record. Do not prune them, do not delete rows that look old, and do not “archive” orders by removing them from the database. If the store is still on legacy posts storage, its orders live in wp_posts and wp_postmeta, and switching to HPOS is a migration project, not a cleanup task.

Sessions

wp_woocommerce_sessions holds one row per active cart session, keyed by a session token. WooCommerce deletes expired sessions on its own schedule, but the table still tracks live visitors, so its size follows traffic rather than catalog size. A store with 2,000 live sessions will have a larger session table than a store with 20, and that is normal.

The cleanup mistake here is truncating the table on a busy store. It logs customers out, empties carts, and does not fix a performance problem that was caused by something else.

Action Scheduler

WooCommerce runs background work through Action Scheduler: order emails, subscription renewals, webhook deliveries, and imports. The queue lives in wp_actionscheduler_actions, with logs in a companion table.

A busy store accumulates history. The scheduled actions documentation shows where to inspect the queue under WooCommerce > Status > Scheduled Actions, including failed jobs and their logs. Look there before deleting anything: a table full of failed actions is a symptom of a broken hook, not a cleanup opportunity.

If the queue is healthy, let Action Scheduler manage its own retention. If it is not, fix the failing job first. Deleting the evidence makes the next failure harder to diagnose.

Reclaim space without pretending you cleaned the data

Deleting rows does not shrink an InnoDB table. The file keeps its size, and data_free grows. OPTIMIZE TABLE rebuilds the table and its indexes, which is the operation that actually returns space to the filesystem.

WP-CLI wraps it:

wp db optimize

The wp db optimize command runs OPTIMIZE TABLE across the database. On InnoDB it is a rebuild, not a metadata refresh: it needs free disk roughly equal to the table size, it takes time proportional to the table, and it competes with production traffic. Schedule it, do not run it during a sale.

Two rules keep this from becoming the expensive part of the cleanup:

  1. Optimize only the tables that shrank. A table that has not lost rows does not need a rebuild.
  2. Check free disk first. A rebuild that fills the disk takes the site down harder than the bloat did.

OPTIMIZE TABLE also does not fix a table that is large because it has a legitimate million rows. It only reclaims space after a delete.

A safe order of operations

The sequence below is boring on purpose. Each step is reversible until the delete, and the deletes come after the measurement.

  1. Back up the database and test the restore. A dump you have never restored is not a backup. The backup plugin comparison covers the tooling, and the WordPress backup guide covers the files-and-database pair; for this job, the database is the part that matters.
  2. Clone to staging and run the measurement queries there. Hosts that provide a one-click staging copy make this a ten-minute step. If yours does not, at least export the database and run the queries against the export.
  3. Clear expired transients. wp transient delete --expired. Low risk, immediate reduction in wp_options.
  4. Audit autoloaded options. Find the largest rows, turn autoload off for admin-only settings, and re-check Site Health. Do not delete options you cannot identify.
  5. Cap and prune revisions. Set WP_POST_REVISIONS, then delete old revisions in batches.
  6. Remove orphaned postmeta only if the count is meaningful. Back up first; there is no undo.
  7. Review WooCommerce’s own tables. Sessions and Action Scheduler are managed by WooCommerce. Fix failing jobs instead of truncating the queue.
  8. Optimize the tables that shrank. Run it in a maintenance window, with free disk available.
  9. Verify the site. Load the homepage, a single post, a category, the cart, and the checkout. Then run the broader functionality and speed check.
  10. Measure again next month. The point of the cleanup is the trend line, not one afternoon of freed megabytes.

The verification step is where cleanup plugins differ. A plugin that deletes rows in one click is easy to install and hard to audit. If you use one, run it on staging first and inspect what it removed. The cache plugin guide is a useful reminder that caching reduces how often those tables are read on the front end, but it does not remove the rows.

What not to do

  • Do not drop tables because a blog post listed them as “unused.” A plugin’s table may hold settings, licenses, or order data that the plugin expects on reactivation.
  • Do not mass-delete postmeta with a LIKE pattern. _elementor_% and _yoast_% look like plugin junk until a page renders without its layout.
  • Do not run OPTIMIZE TABLE on every table every week. It is a rebuild, not a tune-up, and the work costs more than the free space returns.
  • Do not truncate the sessions table on a live store. It logs customers out and empties carts.
  • Do not delete Action Scheduler rows to “speed up” checkout. Failed jobs are a diagnostic signal; the queue runner is the thing to fix.
  • Do not skip the backup because the queries look simple. The dangerous ones always look simple.

When the database is not the bottleneck

A large database is not automatically a slow site. WordPress can serve a 500 MB database quickly if the queries are indexed and the page cache is doing its job. The symptoms that actually point at table bloat are specific:

  • the admin list screens get slower month over month,
  • backups take longer than the window you have,
  • wp_options is the largest table and autoload is over the Site Health threshold,
  • a store’s order search slows down as order count grows.

If the front end is slow but the database is stable, the cause is more likely render-blocking assets or an uncached query. The measured speed walkthrough shows how to attribute that before changing tables. And if the store’s problem is queue throughput rather than table size, the WooCommerce scaling guide covers the layer above the database.

One more distinction: WP-Cron and Action Scheduler are not the same queue. WP-Cron handles core schedules and fires on page requests. Action Scheduler is the job queue WooCommerce uses for background work, and it depends on WP-Cron or a real server cron to run. If jobs are piling up, the WP-Cron replacement guide explains why the trigger matters before you blame the table.

FAQ

How often should I clean the WordPress database?

Measure monthly and clean when a table’s growth or autoload size justifies it. Most sites need expired transients and revision control, not a quarterly deep clean. A store should review sessions and Action Scheduler health more often than it reviews postmeta.

Is it safe to delete expired transients?

Yes. They have already expired, so nothing should depend on them. Deleting all transients is different: that clears valid caches and forces every one of them to rebuild at once, which is why the targeted --expired flag is the right default.

How many post revisions should WordPress keep?

Ten is a practical ceiling for most editorial sites. Set WP_POST_REVISIONS to a number rather than leaving it at true, which means unlimited. Keep more only if your workflow depends on restoring an old draft.

Can I delete orphaned postmeta rows?

Yes, if they belong to posts that no longer exist. Count them first, back up, and exclude any plugin that deliberately stores shared data with post_id = 0. The delete cannot be undone without the backup.

Does optimizing tables speed up WordPress?

Not by itself. OPTIMIZE TABLE reclaims free space after deletes and rebuilds indexes, which can help a table that has been heavily churned. It does not make a well-sized table faster, and the rebuild competes with production traffic while it runs.

Why is wp_options so large?

Usually transients and plugin settings. Some plugins store API responses or cached remote data as options instead of transients, and those rows never expire. The autoload query above shows which rows are both large and loaded on every request.

Should I use a database cleanup plugin?

It is reasonable if you want a UI and a log of what was removed. Run it on staging first and check its output. The risk is not the plugin category; it is a one-click tool that deletes rows without showing you which ones.

Does WooCommerce HPOS make cleanup easier?

It separates order data from wp_posts and wp_postmeta, which makes both sides easier to reason about. It does not remove the need to back up, and it does not make order tables safe to prune. Orders are business records, not cache.

A WP Life
A WP Life

Hi! We are A WP Life, we develop best WordPress themes and plugins for blog and websites.