
WordPress database optimization is the least glamorous speed work I do, and it is often the most effective. Everyone optimises images, installs a caching plugin and argues about hosting – almost nobody looks at the database. Yet on sites older than two or three years, the database is usually where the slowness lives: megabytes of options loaded on every single request, tens of thousands of post revisions nobody will ever read, expired caches that never got deleted, and whole tables left behind by plugins removed in 2022. None of it shows up on the front end until you measure, which is why I call it the invisible speed win.
I have cleaned up hundreds of WordPress databases over 12+ years, from five-page brochure sites to WooCommerce stores with 400,000 orders, and the pattern repeats: the same six or seven kinds of bloat, the same safe fixes, and the same result – a noticeably faster admin, a lower time to first byte, and a hosting bill that stops creeping. This guide walks through how WordPress actually uses its database, where the bloat hides, how to remove it without breaking anything (backup first, always), which tools to trust, what never to touch, and what improvement you can realistically expect.
Table of contents
- How WordPress uses its database – a tour in plain language
- Autoloaded options: the tax on every request
- Post revisions: history you will never read
- Transients: temporary caches that forgot to leave
- Orphaned meta and leftover plugin tables
- Spam, trash and Action Scheduler bloat
- WooCommerce database notes: HPOS, sessions and old orders
- Safe-practice rules before you delete anything
- Tools, honestly: WP-Optimize, WP-CLI, Query Monitor, phpMyAdmin
- What not to touch, and when a slow query needs an index
- The quarterly routine and the results to expect
- Frequently asked questions
How WordPress uses its database – a tour in plain language
Every WordPress site is a PHP application sitting on top of a MySQL (or MariaDB) database. When a visitor requests a page that is not served from cache, WordPress connects to the database, loads its configuration, works out which content to show, fetches that content plus its metadata, and assembles the page. A lean database makes every one of those steps quick; a bloated one makes every step drag – and the admin area, which is almost never cached, feels it worst.
A default install has 12 core tables. You do not need to memorise them, but knowing what lives where turns database cleanup from scary to boring:
| Table | What it stores | How it bloats |
|---|---|---|
| wp_posts | Pages, posts, products, menus, media entries – every content object | Revisions, auto-drafts, trashed items |
| wp_postmeta | Custom fields attached to those objects | Orphaned rows, plugin leftovers, page builder data |
| wp_options | Site settings, plugin settings, transients | Autoload bloat, expired transients, uninstalled plugin options |
| wp_comments / wp_commentmeta | Comments and their metadata | Spam and trashed comments by the thousand |
| wp_users / wp_usermeta | Accounts and per-user settings | Session tokens, plugin per-user rows |
| wp_terms family | Categories, tags, taxonomies | Rarely a problem – mostly leave alone |
Plugins add their own tables on top – a mature site easily carries 40-80 tables, and on audits I regularly find a third of them belong to plugins that were deleted years ago. Two tables dominate almost every cleanup: wp_options, because part of it is loaded on every request, and wp_postmeta, because it grows fastest and is queried constantly. Keep those two healthy and you have done most of the job.
Autoloaded options: the tax on every request
This is the single most important concept in this whole guide. Rows in wp_options have an autoload flag. Everything marked autoload is loaded into memory on every single request – every page view, every admin screen, every REST and AJAX call – whether that data is needed or not. WordPress does this so it does not have to query settings one by one, and on a healthy site the autoloaded set is a few hundred kilobytes. That is fine.
The problem: plugins are careless. They store widget caches, licence blobs, analytics snapshots and entire serialized arrays as autoloaded options, and many never clean up after themselves. When a plugin is uninstalled, its options usually stay. Over the years I have opened sites carrying 5, 10, even 25 MB of autoloaded data. That whole payload is fetched from MySQL, unserialized by PHP and held in memory before WordPress has done anything useful – a tax paid on every request, including the ones your page cache misses: logged-in users, carts, checkouts, search, admin.
Measure it first. One query tells you whether you have a problem:
SELECT ROUND(SUM(LENGTH(option_value))/1024/1024,2) AS autoload_mb FROM wp_options WHERE autoload='yes';
Under 1 MB: healthy, move on. 1-3 MB: worth a look. Above 3 MB: you have found real, measurable slowness. Next, find the offenders:
SELECT option_name, ROUND(LENGTH(option_value)/1024,1) AS size_kb FROM wp_options WHERE autoload='yes' ORDER BY LENGTH(option_value) DESC LIMIT 20;
With WP-CLI it is even simpler: wp option list --autoload=on --fields=option_name,size_bytes --format=table (recent WP-CLI versions also ship wp doctor style checks, and hosts with WP-CLI 2.x can sort with a one-line pipe). The top 20 usually tells the whole story – I typically see one or two rows of 500 KB+ from a page builder cache, an abandoned security plugin’s log, or a social plugin’s feed snapshot.
Safe fixes, in order of caution:
- Options from plugins you still use: check the plugin’s settings for a “clear cache” or “purge data” button first; many oversized options are caches the plugin will happily rebuild smaller.
- Options from plugins you removed: confirm the prefix matches the dead plugin (search the name), then delete the row – or, if you are nervous, flip it to
autoload='no'first and watch the site for a week:UPDATE wp_options SET autoload='no' WHERE option_name='rogue_option_name'; - Options you cannot identify: leave them. An unidentified 4 KB row costs nothing; deleting it blind can cost an afternoon.
On one client’s site – an eight-year-old business site in Germany – autoload was 11.8 MB, almost all of it from two long-uninstalled plugins. Twenty minutes of careful deletion took it to 600 KB, and time to first byte on uncached pages dropped from roughly 900 ms to under 350 ms. No caching plugin, no hosting change – just removing dead weight the server had been lifting on every request for years.
Post revisions: history you will never read
Every time you click Update, WordPress stores a complete copy of the previous version as a revision in wp_posts, with its own rows in wp_postmeta. By default there is no limit. A page edited weekly for five years carries 250+ full copies of itself; a site built with a page builder is worse, because each revision drags its heavy meta along. I audited a 60-page site last year with 9,400 revision rows – the actual content was under 4% of wp_posts.
Revisions rarely slow the front end directly, but they inflate every backup, slow admin queries and searches, and turn wp_postmeta into a swamp. Two fixes, both safe:
- Cap future revisions in wp-config.php, above the “That’s all, stop editing” line:
define( 'WP_POST_REVISIONS', 5 );. Five is plenty of undo history for a business site. Do not set it to false/zero – keeping a few revisions has saved more than one client from an editing accident. - Delete the existing pile. With WP-CLI:
wp post delete $(wp post list --post_type=revision --format=ids) --force. With WP-Optimize: tick only “Clean all post revisions” and run it. Either way, this only removes rows WordPress itself labels as revisions – your live content is untouched.
While you are in wp_posts, clear the small stuff too: auto-drafts (wp post list --post_status=auto-draft) and items sitting in trash for months. WordPress purges trash after 30 days by default, but plenty of sites have that disabled or overridden.
Transients: temporary caches that forgot to leave
Transients are WordPress’s built-in temporary cache: a plugin stores an API response or an expensive calculation with an expiry time, and reads it back until it expires. Sensible design – with one flaw. Expired transients are not deleted on schedule; they are only removed when something asks for them again or when a housekeeping routine catches them. If a plugin stops asking (or gets uninstalled), its expired transients sit in wp_options forever. Sites that fetch external feeds – currency rates, social content, weather, licence checks – accumulate them by the thousand.
Count them if you are curious: SELECT COUNT(*) FROM wp_options WHERE option_name LIKE '_transient_timeout_%';. The fix is one of the safest in this entire guide, because transients are disposable by definition – any plugin that needs one will simply regenerate it:
- WP-CLI:
wp transient delete --expired– my standard first move on any cleanup. If the site misbehaves with stale cached data,wp transient delete --allis also safe; the first uncached page view will be slower while caches rebuild, and that is all. - WP-Optimize: the “Remove expired transient options” task does the same on a schedule.
One nuance: on hosts with a persistent object cache (Redis or Memcached – common on managed WordPress and the setups I cover in the high-traffic scaling guide), transients live in the object cache instead of wp_options, and this whole section mostly takes care of itself. That alone is a good argument for Redis on busier sites.
Orphaned meta and leftover plugin tables
When a post is deleted, its wp_postmeta rows should go with it – and usually do. But plugin bulk operations, failed imports, direct database edits and plugin uninstalls leave orphans: meta rows pointing at posts that no longer exist, comment meta for deleted comments, user meta for deleted users. Individually tiny, collectively they add up to hundreds of thousands of rows that every JOIN has to wade through. Finding orphaned post meta is a classic query:
SELECT COUNT(*) FROM wp_postmeta pm LEFT JOIN wp_posts p ON pm.post_id = p.ID WHERE p.ID IS NULL;
If the count is in the hundreds, ignore it. In the tens of thousands, clean it – WP-Optimize’s “Clean post meta data” task does exactly this JOIN-and-delete, as does the equivalent DELETE query run on a backed-up database.
Leftover tables are the bigger, more satisfying win. Plugins create their own tables freely, and most do not remove them on uninstall (some deliberately, in case you reinstall). List every table with wp db tables or in phpMyAdmin and read the names: wp_wfHits and friends belong to Wordfence, wp_rank_math_* to Rank Math, wp_yoast_* to Yoast, wp_ec_* or wp_wpforms_* and so on – the prefix almost always names the plugin. My rule for dropping a table, applied strictly:
- Identify it positively. Search the table name plus “plugin” – two minutes on any search engine settles which plugin created it.
- Confirm the plugin is gone – not deactivated, actually deleted, with no plan to return. A deactivated plugin’s tables must stay.
- Check the contents – browse a few rows. Logs and cache rows are safe to lose; anything that looks like user-entered data (form entries, orders, bookings) gets exported first even if the plugin is gone.
- Backup, then drop. If any doubt remains, rename the table instead (add a suffix like
_old), wait two weeks, then drop it.
I recently removed 23 tables and 1.1 GB from a site that had been through three agencies and four security plugins. Nothing broke, because nothing was using them – that is the point of the identification step.
Spam, trash and Action Scheduler bloat
The unglamorous leftovers, quickly:
- Spam comments. Akismet and similar tools catch spam but keep it for review. On old blogs I routinely find 50,000-200,000 spam comments plus their commentmeta. Empty the spam queue (
wp comment delete $(wp comment list --status=spam --format=ids) --force) and consider disabling comments on old posts if nobody real comments any more. - Trashed posts and comments. Trash is a safety net, not an archive. If it has been there longer than a month, it goes.
- Action Scheduler. This one deserves its own bullet in bold, because it is the fastest-growing table on many modern sites. Action Scheduler is a background job queue shipped inside WooCommerce and used by many major plugins. It logs every completed job in
wp_actionscheduler_actionsandwp_actionscheduler_logs– and on a busy store those tables reach millions of rows. Completed and failed actions older than the retention period (30 days by default, and even that is generous) are pure history. Check the counts under Tools then Scheduled Actions; clean-up is built in and safe, and a filter can shorten retention to a week:add_filter( 'action_scheduler_retention_period', function() { return WEEK_IN_SECONDS; } ); - Plugin log and session tables. Security plugins logging every login attempt, redirect managers logging every 404, form plugins storing every submission, SMTP plugins storing every sent email. Logs are useful for a few weeks and dead weight after. Every serious logging plugin has a retention setting – set it to 14-30 days and the table stops growing.
None of this junk needs deep expertise to remove. It needs someone to actually look – which is why this whole category belongs in a routine (mine is part of the maintenance checklist I run for clients) rather than a one-off heroic rescue.

WooCommerce database notes: HPOS, sessions and old orders
Stores deserve a special word, because WooCommerce is both the heaviest database user in the WordPress world and the one where careless cleanup does real damage – orders are legal and accounting records, not clutter.
- HPOS (High-Performance Order Storage). Historically WooCommerce stored orders as posts, spreading each order across wp_posts and dozens of wp_postmeta rows – the main reason big stores slowed down. HPOS moves orders into dedicated, properly indexed tables and has been the default for new stores for a while now. If you run an older store still on legacy post storage, migrating to HPOS (WooCommerce, Settings, Advanced, Features) is the single biggest database improvement available to you – test it on staging first, especially with older plugins that touch orders directly.
- Sessions.
wp_woocommerce_sessionsholds carts for guests and should recycle itself; after certain plugin conflicts I have seen it stuck at hundreds of thousands of rows. Expired sessions are safe to clear (WooCommerce, Status, Tools). - Old order data. Do not delete orders to “optimise” – keep them for as long as your accountant and local law require, which is typically years. What you can safely trim: cancelled and failed orders older than a few months (they hold no money and no obligations – export a CSV first if you want the record), and draft/pending orders from bot traffic.
- Analytics and reports. WooCommerce’s analytics tables rebuild from orders; if they are corrupted or bloated there is a rebuild tool under Status, Tools. Slow reports on big stores are usually an indexing or hosting conversation, not a deletion one.
Safe-practice rules before you delete anything
Everything above is safe because of the discipline around it. The database is the one part of WordPress with no undo button – files can be re-uploaded, plugins reinstalled, but a dropped table with no backup is simply gone. My rules, unchanged for a decade:
- Backup first. Every time. No exceptions. A full database export takes two minutes (
wp db export backup-before-cleanup.sqlor your backup plugin’s manual run) and turns every mistake in this guide into a five-minute restore instead of a disaster. If your backup situation is shaky, fix that before any cleanup – my backup and disaster recovery guide covers the full setup, including actually testing a restore. - Prefer staging for the scary parts. Deleting expired transients on production is fine. Dropping tables, cleaning orphaned meta at scale, or an HPOS migration belongs on a staging copy first. Most decent hosts give you one-click staging; use it.
- One change at a time. Run one cleanup, check the site (front end, admin, checkout if it is a store), then the next. If you do six things at once and something breaks, you have six suspects.
- Measure before and after. Note the database size, the autoload size and a TTFB reading before you start. Without a before number, you cannot know what worked – and you will want the numbers for the client anyway.
- Low-traffic window for stores. Table operations lock rows; on a busy shop, run heavy cleanups when orders are quiet.

Tools, honestly: WP-Optimize, WP-CLI, Query Monitor, phpMyAdmin
You do not need a paid tool for any of this. You need two or three of the following, used for what each is good at:
- WP-Optimize (and its class of plugins – Advanced Database Cleaner is the other one I rate). The right choice for non-developers and for scheduled housekeeping: revisions, auto-drafts, trash, spam, expired transients, orphaned meta, all with checkboxes. Two honest caveats: untick anything you do not understand rather than trusting “select all”, and do not leave a cleanup plugin active year-round just for a quarterly task – install, run, remove, or use its scheduler deliberately. Advanced Database Cleaner’s paid tier is genuinely useful for one thing: attributing orphaned options and tables to the plugin that created them.
- WP-CLI. My daily driver, and the reason cleanups take minutes: every command is precise, scriptable and loggable. The core recipe set:
wp db size --tablesto see where the weight is,wp transient delete --expired, the revision deletion one-liner from above,wp comment deletefor spam,wp db exportbefore everything, andwp db optimizeat the end to have MySQL reorganise the freed space. If you manage more than one site, ten lines of shell script make this repeatable across all of them. - Query Monitor. Not a cleanup tool – a diagnosis tool, and the best free one in WordPress. Install it when a specific page is slow: it shows every database query the page ran, how long each took and which plugin triggered it. That is how you find out that a “slow database” is actually one badly written plugin query, which no amount of cleanup will fix – only replacing the plugin or indexing will.
- phpMyAdmin (or Adminer). Fine for looking: browsing tables, running the read-only SELECT queries in this guide, checking sizes. Be careful when writing: there is no confirmation worth the name, no undo, and a mistyped DELETE without a WHERE clause is a career moment. My rule – reads freely, writes only with a fresh export in hand, structural changes preferably via WP-CLI or a migration script instead.
What I do not recommend: “one-click database optimizer” features inside giant do-everything plugins, running random optimisation SQL from forum posts, and any tool that will not tell you exactly which rows it is about to delete.
What not to touch, and when a slow query needs an index
Cleanup confidence comes from knowing the boundaries. Leave these alone:
- Core table structure. Delete junk rows, never alter core tables’ columns, engines or schemas. WordPress updates assume the standard structure.
- wp_users and wp_usermeta beyond obvious plugin leftovers. Session tokens look like clutter and are not worth the risk of logging everyone out or breaking capabilities.
- Anything you cannot positively identify. Unidentified rows are innocent until proven bloat.
- Orders, form entries, bookings, anything legally or financially meaningful – export before touching even the safe subsets.
- Tables of deactivated (not deleted) plugins – deactivated means “coming back”, and the data must be there when it does.
And a boundary in the other direction: sometimes the database is clean and still slow, because a plugin runs a query that scans a huge table without an index – postmeta lookups on large stores are the classic case. Adding an index is a real fix (a well-placed index on a meta query can turn 4 seconds into 40 milliseconds), but it is developer territory: the wrong index wastes memory and slows writes, and indexes on core tables need re-checking after major updates. If Query Monitor shows one query eating hundreds of milliseconds on every load, that is the point to hand the evidence to a developer rather than reach for another cleanup plugin. This is exactly the kind of job I take on inside my speed optimisation service – the cleanup layer is teachable, the query layer is where experience pays.
The quarterly routine and the results to expect
Database health is not a project, it is a habit. Once the initial cleanup is done, a quarterly pass keeps a site permanently lean – 30 to 45 minutes, in this order:
- Full database export, saved off-server.
- Record the numbers: total DB size, autoload size, TTFB on an uncached page.
- Expired transients out; spam and trash emptied.
- Revisions beyond the cap deleted (the wp-config cap keeps this small forever).
- Autoload re-checked – one query – and any new offender investigated.
- Log and Action Scheduler tables glanced at; retention settings still sane.
- A look for tables from any plugin removed this quarter.
wp db optimize, then record the after numbers next to the before.
What results should you expect? Honest ranges from my own client work: a site that has never been cleaned typically loses 30-70% of its database size in the first pass; TTFB on uncached requests improves anywhere from barely-measurable (if autoload was already healthy) to 400-600 ms (if it was not); wp-admin gets snappier almost every time, which clients notice more than any lab metric; and backups get smaller and faster, which you notice on restore day. What cleanup will not do: rescue slow hosting, fix render-blocking front-end assets (that is the territory of the complete speed guide), or compensate for a plugin that is slow by design. It removes one whole layer of invisible drag – and on old sites, that layer is thick.
Want your database cleaned properly, with numbers to prove it?
I do this exact work as part of my WordPress speed optimisation service, and keep it done as part of ongoing maintenance – backup first, staging for anything risky, before/after measurements in the report. Have a look at the portfolio, or send me your site and I will reply within 24 hours with what I would clean and a fixed price.
Frequently asked questions
What is WordPress database optimization?
It is the removal of accumulated junk from a WordPress database – autoloaded option bloat, old revisions, expired transients, spam and orphaned plugin data – plus reorganising tables so MySQL works with less weight. The result is faster uncached page loads and a quicker admin.
Is it safe to clean a WordPress database?
Yes, if you take a full backup first, change one thing at a time and only delete what you can positively identify. The risky failures all come from skipping one of those three rules.
How often should I optimise my WordPress database?
A thorough first cleanup, then a 30-45 minute pass every quarter. Sites with a revision cap and sensible log retention settings barely accumulate new bloat between passes.
Do database cleanup plugins like WP-Optimize really work?
Yes – for revisions, transients, spam and orphaned meta they do exactly what the manual queries do, with checkboxes. They do not fix autoload bloat you have not investigated, slow plugin queries or missing indexes.
What is autoloaded data and why does it matter?
Options flagged as autoload are loaded from the database on every single request, cached or not. A healthy site carries under 1 MB; old sites often carry 5-20 MB of dead plugin data, and trimming it measurably cuts time to first byte.
How many post revisions should I keep?
Around five. Set define( 'WP_POST_REVISIONS', 5 ); in wp-config.php and delete the historical pile once. Do not disable revisions completely – a little undo history is worth keeping.
Will database cleanup speed up my WooCommerce store?
Usually, yes – Action Scheduler logs, sessions and autoload bloat hit stores hardest because carts and checkouts bypass page caching. The biggest single win for older stores is migrating orders to HPOS, tested on staging first.