On this page
Before we start, let's draw an important line. This article deals with cleaning up the WordPress database from the site owner's perspective: revisions, transients, autoload, orphaned data, things you do yourself from the dashboard, phpMyAdmin or the command line without deep knowledge of database engineering. Engine-level optimization (indexes, tuning slow queries, MySQL server configuration, object caching with Redis) is a deeper topic concerning the general performance of any database, and we've given it its own guide: database optimization (the general guide). The difference in short: the general one = infrastructure and query performance; this one = content maintenance done by the site owner. The two complement each other, and neither replaces the other.
Why does the WordPress database in particular bloat?
WordPress doesn't store your pages as ready-made files; it builds them on every visit from a relational database (MySQL or MariaDB). Every post, every comment, every setting and every plugin option is a row in a table. This design is extremely flexible, but it means the database keeps growing, and a large part of that growth is surplus with no value: duplicate copies, temporary data that has expired, and remnants of content you deleted years ago whose traces remain.
The problem is that WordPress doesn't clean up after itself automatically. When you delete a post, its core data disappears from wp_posts, but its custom fields in wp_postmeta may remain dangling without a parent. When you delete a plugin, the tables and options it created stay scattered around the database. And when temporary data (a transient) expires, WordPress doesn't delete it proactively; it waits until it's requested again to discover that it has expired. The result: a database where dead layers accumulate like dust behind the furniture.
The danger of this bloat isn't the database's size on disk (a few megabytes won't hurt you) but one item in particular: autoload options. These are options WordPress loads into memory on every page request before doing anything else. If these options swell to hundreds of kilobytes, you pay a tax on every visit for every visitor, and that's where the effect on speed and Core Web Vitals clearly shows. That's why we'll give autoload the lion's share of attention later.
The structure of WordPress tables: a map before cleaning up
Before you touch anything, you need to know what you're touching. A default WordPress installation creates 12 core tables, all with the wp_ prefix (it may be different in your installation for security reasons). Understanding each table's role keeps you from deleting what you think is junk but is actually the backbone of your site.
| Table | Role | Relation to bloat |
|---|---|---|
wp_posts | Posts, pages and attachments + revisions and auto-drafts | A major source of bloat (revisions) |
wp_postmeta | The custom fields for each item in wp_posts | Swells with orphaned data and plugin fields |
wp_options | The most important for performance: settings + transients + autoload options | The most dangerous source of bloat (autoload) |
wp_comments | Comments and their status (approved/spam/trash) | Swells with spam and trash |
wp_commentmeta | Comment metadata | Orphaned data after comments are deleted |
wp_users | User accounts | Rarely bloats |
wp_usermeta | User preferences and data | May swell with membership plugins |
wp_terms | Categories and tags (the names) | Limited growth |
wp_term_taxonomy | Each term's type (category/tag) and description | Limited growth |
wp_term_relationships | Links posts to categories/tags | Orphaned data after posts are deleted |
wp_termmeta | Term metadata | Limited growth |
wp_links | The old "Links" (Blogroll) system, now abandoned | Usually empty, old leftovers |
The golden rule here: the tables aren't junk; the surplus rows inside them are. We'll never delete a table from this list; we'll delete specific rows with precise conditions. The only tables that may be deleted entirely are tables created by plugins you've since removed, and we'll handle those carefully in a separate section.
The sources of bloat in WordPress and how to clean up each one
Now to the heart of the matter. Each source of bloat has a different nature, a different cleanup method and a different level of risk. The following table is your complete map, and we'll detail each one after it.
| Source of bloat | What is it? | Where it lives | Risk | Safest cleanup method |
|---|---|---|---|---|
| Post revisions | A copy saved every ~60s; one post may collect 50+ | wp_posts (post_type='revision') | Leaves orphans | WP-CLI or SQL + orphan cleanup |
| Auto-drafts | auto-draft from an editor that was never published | wp_posts (post_status='auto-draft') | Low | SQL/WP-CLI |
| Content in the trash | Deleted posts/pages that were never emptied | wp_posts (post_status='trash') | Medium (check first) | SQL/WP-CLI |
| Spam and trashed comments | Comments marked as spam or deleted | wp_comments | Low | SQL/WP-CLI |
| Expired transients | Temporary data that expired but wasn't deleted | wp_options | Low (but annoying) | wp transient delete --expired |
| Bloated autoload options | Options loaded on every request | wp_options (autoload) | The most harmful to performance | Diagnose, then adjust selectively |
| Orphaned data (meta/relationships) | postmeta/commentmeta with no parent | wp_postmeta, wp_commentmeta | Medium | LEFT JOIN … IS NULL |
| pingbacks / trackbacks | Old pingbacks/trackbacks | wp_comments | Low | Depends on your needs |
| Deleted plugins' tables | Tables left behind after a plugin is deleted | The whole database | Medium (make sure!) | Manual inspection/a specialized plugin |
| WooCommerce sessions | Old visitor carts and sessions | wp_options / WC tables | Medium (wipes carts) | WooCommerce's own tools |
Revisions: the biggest silent source of bloat
Every time you click "Save" or "Update" in the WordPress editor, a complete copy of the post is saved as a "revision." Add to that the autosave that runs about every 60 seconds while you write. The result is that a single post edited over several sessions can leave behind 50 revisions or more, each one a complete copy taking up space in wp_posts and leaving fields in wp_postmeta.
Revisions are useful while writing (they let you roll back), but keeping them forever without a limit is wasteful. Cleaning them up is relatively safe, but there's a subtle trap here: deleting revisions with a simple DELETE statement on wp_posts leaves the related wp_postmeta and wp_term_relationships rows orphaned. That's why the cleanest method is always WP-CLI (because it goes through WordPress's logic and deletes related data), and if you have to use SQL, follow it with orphan cleanup (which we'll explain shortly).
Expired transients: the garbage nobody sweeps up
Transients are a WordPress caching mechanism: they store data with a time-based expiry (for example, the result of a heavy query for an hour). They're stored in wp_options as a pair: _transient_<name> for the value and _transient_timeout_<name> for the expiry time. The core problem: WordPress doesn't delete expired transients proactively; it waits until one is requested again to discover that it has expired, then deletes it. So if a plugin creates a transient that's never requested again, it stays in the database forever.
With many active plugins, thousands of expired transients can pile up. Worse: some of them may be autoload=yes, so they're loaded on every request. Cleaning them up is one of the safest and most useful operations. The rule when deleting manually: delete the _transient_ and _transient_timeout_ pair together, never one without the other. WP-CLI does this with a single clean command.
Autoload: the item you should really focus on
This is the most important section of the whole article. The autoload column in wp_options determines which options WordPress loads automatically at the start of every page request, all at once, before it knows whether it will need them. The logic: saving separate queries later. But when a plugin misbehaves and puts a huge option (a settings array, a log, an internal cache) on autoload, you're loading that weight onto every visitor on every page.
Here's a crucial detail that WordPress changed recently: since versions 6.6/6.7, the autoload column no longer stores just yes/no, but new values: on, off, auto, auto-on, auto-off. The old yes/no values are now deprecated (they still work for backward compatibility, but WordPress now writes the new values). In addition, any option larger than 150 KB isn't autoloaded even if that was requested. In practice, this means any old diagnostic query that looks only for autoload='yes' will miss options set to the new values and give you an incomplete picture. The correct query today uses IN, not =:
SELECT option_name, LENGTH(option_value) AS size, autoload
FROM wp_options
WHERE autoload IN ('yes','on','auto','auto-on')
ORDER BY size DESC
LIMIT 50;Run this in phpMyAdmin (or any SQL interface on your database), and you'll get a list of the 50 largest autoloaded options, sorted by size in descending order. Read their names: if you see a huge option starting with _transient_, it's a stray transient that should be deleted; if you see an option named after a well-known plugin, look in its settings for a "cleanup" option or contact its developer. To find the total:
SELECT ROUND(SUM(LENGTH(option_value))/1024, 1) AS autoload_kb
FROM wp_options
WHERE autoload IN ('yes','on','auto','auto-on');The target threshold: keep the total autoload size under about 800 KB to 1 MB. Going well beyond that is a sign of a bloated option draining every request. Don't switch an option from autoload to off at random; an active plugin may need it on every page. The sound approach: identify the huge option, understand where it comes from, then fix the source (delete a transient, adjust a plugin setting, or remove an abandoned plugin). This item alone can give you a bigger TTFB improvement than everything else.
To understand why the IN query has become necessary rather than just a precaution, we need to know exactly what WordPress changed in 6.6 and what followed in 6.7. Before 6.6 the column was purely binary: yes meant load it on every request, and no meant don't. From 6.6, the column distinguishes between an explicit manual decision and an automatic decision WordPress made on your behalf. on and off mean a developer (or you) set the value explicitly through the autoload parameter of add_option, while auto, auto-on and auto-off mean WordPress decided on autoloading itself based on the option's size. This distinction isn't cosmetic: it lets WordPress make a smart default decision without overriding a decision the developer made deliberately.
The decisive rule introduced in 6.6 is the 150 KB threshold: any new option added without an explicit autoload value whose size exceeds this limit is automatically set by WordPress to auto-off, excluding it from autoloading to protect the performance of every request. This is excellent preventive behavior, but note: it isn't applied retroactively. Huge options that a plugin planted before 6.6 and that are still yes will stay yes and be loaded on every request until you intervene manually; the threshold protects new options only. That's why manual diagnosis with the query above remains necessary even on the latest version.
Now it's clear why the old query WHERE autoload = 'yes' has become a real diagnostic error, not just a shortcoming: on a modern site, options added by WordPress or plugins after the upgrade may carry on, auto or auto-on, and all of them are actually loaded on every request even though they aren't yes. If you settled for ='yes', you'd see only part of the real load and think autoload was healthy while it's actually bloated. That's why the correct condition is IN ('yes','on','auto','auto-on'), which collects everything that's autoloaded regardless of where the decision came from. Note that we deliberately exclude off and auto-off, because they aren't loaded, so there's no point counting them in the autoload budget.
Orphaned data: leftovers without a parent
When posts or comments are deleted, their metadata is sometimes left dangling. A row in wp_postmeta pointing to a post_id that no longer exists in wp_posts is an orphaned row: it serves no purpose, weighs down the table and slows its queries. The safest way to delete it is the LEFT JOIN … IS NULL pattern, which deletes only rows that truly have no parent:
DELETE pm FROM wp_postmeta pm
LEFT JOIN wp_posts p ON p.ID = pm.post_id
WHERE p.ID IS NULL;And the same pattern for orphaned comment metadata:
DELETE cm FROM wp_commentmeta cm
LEFT JOIN wp_comments c ON c.comment_ID = cm.comment_id
WHERE c.comment_ID IS NULL;This pattern is precise because it doesn't guess: it deletes exclusively what has no parent in the reference table. But be careful: always check the count before deleting (we'll explain the SELECT-before-DELETE rule shortly), because some plugins store data that "looks orphaned" but actually points to their own IDs rather than to real posts, and deleting it breaks them.
Why LEFT JOIN … IS NULL specifically, and not a subquery with NOT IN? The difference lies in both logic and safety. LEFT JOIN joins every row in wp_postmeta to its potential parent in wp_posts via post_id = ID; if it finds no parent, all the wp_posts columns come back NULL, and the WHERE p.ID IS NULL condition catches exactly that case: rows with no real parent. WHERE post_id NOT IN (SELECT ID FROM wp_posts) looks equivalent but hides a nasty trap: if the subquery contains a single NULL value, NOT IN returns NULL for the whole comparison and silently deletes nothing. You think you've cleaned up when you haven't. LEFT JOIN is immune to this mistake, and usually faster on large tables because the query optimizer treats it as a join rather than a repeated membership check.
Before running the delete statement, turn it into a count to find out the real size, using exactly the same structure, with DELETE swapped for SELECT COUNT(*):
SELECT COUNT(*) FROM wp_postmeta pm
LEFT JOIN wp_posts p ON p.ID = pm.post_id
WHERE p.ID IS NULL;If the count shows a reasonable number that matches the content you've deleted, you're on solid ground. If it shows tens of thousands on a small site, stop and inspect a sample with SELECT pm.meta_key, pm.meta_value before you touch anything; you may be dealing with a plugin that stores data in an unusual way. The same pattern applies to a third table that's often forgotten: wp_term_relationships, where links between deleted posts and their categories are left dangling without a post. But be even more careful here: the taxonomy structure is spread across three related tables, and cleaning it manually is riskier than postmeta. It's safer to let WordPress or WP-CLI handle it, because they update the counters (count) in wp_term_taxonomy automatically, which your manual deletion won't do.
SQL commands for manual cleanup: with great care
If you're comfortable with phpMyAdmin or any SQL interface, these commands clean up common sources of bloat directly. Before running any of them, read the safeguards section at the end of the article; the backup isn't optional.
Revisions, auto-drafts and trash:
-- Delete all revisions (⚠️ leaves orphaned postmeta; clean orphans after, or use WP-CLI)
DELETE FROM wp_posts WHERE post_type = 'revision';
-- Delete auto-drafts
DELETE FROM wp_posts WHERE post_status = 'auto-draft';
-- Empty the trash (make sure you don't want any of it first)
DELETE FROM wp_posts WHERE post_status = 'trash';Spam comments:
DELETE FROM wp_comments WHERE comment_approved = 'spam';Two rules you never compromise on in phpMyAdmin:
First, SELECT before DELETE: before you delete, swap the word DELETE for SELECT COUNT(*) (or SELECT * to preview a sample) with the same condition, and see how many rows you'll affect. If you expected 200 revisions and the count shows 40,000, something is wrong in your understanding or your condition, so stop. Example:
SELECT COUNT(*) FROM wp_posts WHERE post_type = 'revision';Second, there's no undo in phpMyAdmin: once you click "Go" on a DELETE statement, it's done. No "cancel" button, no recycle bin. The only way back is the backup. That's why you should never run a single delete statement without a backup ready.
Deleting expired transients manually with SQL is harder, because it requires matching the value/timeout pair and comparing times, and that's exactly what WP-CLI does safely in a single command, so don't complicate your life.
WP-CLI: the cleanest and safest method
If your host gives you SSH command-line access, WP-CLI is the best cleanup tool of all. The reason it beats raw SQL: its commands go through WordPress's own logic, so they delete related data automatically (the revision and its metadata together) instead of leaving orphans behind. Here are the basic commands:
# Delete all expired transients (very safe)
wp transient delete --expired
# Delete all revisions with their related data (leaves no orphans)
wp post delete $(wp post list --post_type=revision --format=ids) --force
# Delete spam comments with their data
wp comment delete $(wp comment list --status=spam --format=ids) --force
# Clean and optimize tables (calls OPTIMIZE TABLE internally)
wp db optimizeThe --force flag means permanent deletion (skipping the trash), which is what you want for revisions and spam, since there's no point sending them to a bin. Note that wp post delete without --force will only send items to the trash, which is the opposite of what you want here.
Another advantage: WP-CLI can be automated. You can schedule wp transient delete --expired weekly through cron on the server without touching the database manually. But keep the scheduling conservative: expired transients are safe to schedule, while automatically deleting the trash or revisions is better left to a deliberate manual decision.
Scheduling through real server cron (not the pseudo WP-Cron that only runs on visits) is the clean way to automate safe cleanup. You add a line to the crontab with the crontab -e command, taking care to specify the full path to wp and to the site, because cron runs in a minimal environment that doesn't know your shortcuts:
# Every Sunday at 3 a.m.: delete only expired transients
0 3 * * 0 /usr/local/bin/wp transient delete --expired --path=/var/www/html --quietThe --path flag tells WP-CLI where WordPress is installed (necessary because cron doesn't run from inside the site folder), and --quiet suppresses output so cron doesn't email you on every run. Note that the schedule is limited to expired transients alone, and that's a rule, not a show of caution. Expired transients are, by definition, data that has lost its validity, so deleting them loses nothing. Revisions and the trash are another story: a revision today may be your safety net tomorrow when you need to roll back, and a post in the trash may be a mistaken deletion you haven't noticed yet. Automating their deletion means a human error (you deleted the wrong post) turns into a permanent loss before you notice. The golden rule of automation: automate what can be lost without regret, and keep what you might regret under a deliberate manual decision. If you want deeper scheduling (such as deleting revisions older than a year), make it monthly, not daily, and only after you've set WP_POST_REVISIONS to stop the build-up at its root.
| Operation | WP-CLI command | Deletes related data? | Safety level |
|---|---|---|---|
| Expired transients | wp transient delete --expired | Not needed | Very safe (can be scheduled) |
| Revisions | wp post delete $(...) --force | Yes | Safe (check the count) |
| Spam comments | wp comment delete $(...) --force | Yes | Safe |
| Optimizing tables | wp db optimize | — | Safe (may lock tables briefly) |
Stop bloat at its root: wp-config.php constants
Cleanup is the cure, but prevention is better. By adding constants to the wp-config.php file (above the line /* That's all, stop editing! */), you limit the sources of bloat before they arise. A key note: these constants don't delete what already exists; they only stop future growth. So if you already have 40,000 revisions, you need to delete them manually first, and the constant will then stop them from piling up again.
| Constant | What it does | Suggested value | Warning |
|---|---|---|---|
WP_POST_REVISIONS | Limits the number of revisions saved per post | 5 (or false to disable completely) | Doesn't delete existing revisions |
AUTOSAVE_INTERVAL | Spaces out autosaves (in seconds) | 120 (instead of 60) | Reduces how often automatic revisions are created |
EMPTY_TRASH_DAYS | How many days deleted items stay in the trash | 7 (or 0 to disable the trash) | 0 means immediate deletion with no safety net |
Practical examples to add to wp-config.php:
// Keep only the last 5 revisions per post
define( 'WP_POST_REVISIONS', 5 );
// Space autosaves out to two minutes
define( 'AUTOSAVE_INTERVAL', 120 );
// Empty the trash automatically after 7 days
define( 'EMPTY_TRASH_DAYS', 7 );Note the WP_POST_REVISIONS = false option: it disables revisions completely. I don't recommend it for an active content site because it takes away your ability to roll back, but it makes sense for a site whose content is rarely edited. The golden mean is a small number such as 5 or 10, which gives you a safety net without bloat. As for EMPTY_TRASH_DAYS = 0, use it with caution: it deletes everything you send to the trash immediately and irreversibly, which you don't want if you sometimes delete quickly and regret it later.
The truth about OPTIMIZE TABLE and "overhead"
This is where a common exaggeration spreads. Many guides and plugins show you an "overhead" figure (wasted space inside tables) and imply that running OPTIMIZE TABLE will make a big difference to speed. The truth is more nuanced, and it depends on the storage engine:
- On MyISAM (the old engine):
OPTIMIZE TABLEactually removes fragmentation and reclaims wasted space, but it locks the table during the operation (a temporary pause on writes). - On InnoDB (the default in modern WordPress): the command doesn't "optimize" in the same sense; it rebuilds the table, so its benefit is limited. Some fragmentation in InnoDB is normal and nothing to worry about.
Let's bust the myth explicitly, because it's widespread enough to deserve detail. When you run OPTIMIZE TABLE on an InnoDB table, there's no native "optimize" operation for this engine at all, so MySQL implicitly maps it to ALTER TABLE … FORCE, meaning rebuilding the table from scratch, copying it entirely, and then swapping it in. The result is that it returns some space to the operating system and reorders the pages, but it doesn't perform the magic you expect: InnoDB's "wasted" space (what interfaces such as phpMyAdmin call overhead) isn't literally wasted; it's usually reserved pages that InnoDB reuses automatically when new data is inserted. So by rebuilding you free them now, only for the engine to reserve them again later: a pointless cycle most of the time.
And it has a real cost you should be aware of: the rebuild needs temporary disk space equal to the size of the table itself (because it copies it), puts heavy I/O pressure on a large table, and may block writes while it runs on some configurations. On a wp_postmeta table of several gigabytes, this can take minutes during which your site suffers. Hence the decisive practical difference: on MyISAM the command offers a tangible benefit (removing real fragmentation) in exchange for locking the table, while on InnoDB the benefit is marginal and the cost remains, so you pay roughly the same price for a much smaller return. The rule: on InnoDB, don't run OPTIMIZE TABLE routinely; reserve it for one exceptional case, after a massive one-off deletion (millions of rows) after which you really want to return disk space to the system. Outside that case, it's noise with no value.
The practical takeaway: don't overstate the importance of OPTIMIZE TABLE itself. The real value of cleanup comes from deleting surplus rows (revisions, transients, spam, orphans) and trimming autoload, not from the optimize command itself. wp db optimize or the "optimize tables" button in plugins is a nice finishing step that reclaims some space after deletion, but it isn't the hero. If you spend all your time clicking "optimize" without dealing with the sources of bloat, you're polishing a surface, not cleaning it.
Cleaning up with plugins: convenience vs. risk
Not every site owner is comfortable with SQL or SSH, and that's where cleanup plugins come in. They offer a button interface for everything we've explained, with automatic scheduling. But every convenience has a price, and the price of these plugins is lost visibility: you click a button and the plugin deletes things you can't see. That's why the rule when using them is: understand what each option does before enabling it, and start without aggressive scheduling.
| Plugin | Strengths | Limits and risks |
|---|---|---|
| WP-Optimize | The most widely used (1M+ installs), thorough cleanup + scheduling + table optimization, with an easy interface available in Arabic | An "all-in-one" tool (cache + image compression + cleanup) that can weigh down the site; the default schedule may be aggressive |
| Advanced Database Cleaner | Excellent at detecting orphaned data and tables left by deleted plugins | Its most important feature (orphaned table detection) is mainly in the paid version; "orphan" detection isn't infallible |
All cleanup plugins, these two included, share two limits you need to understand well:
First, aggressive scheduling can delete something you need. If you set the plugin to clean daily and include "trash," it may wipe a post you deleted by mistake before you notice. Keep scheduling conservative: expired transients weekly is fine, but keep the trash and revisions under a manual decision.
Second, "orphan" detection isn't infallible. When a plugin tells you that 5,000 rows in wp_postmeta are "orphaned," that's its own judgment, based on its own logic. Some of those rows may belong to an active plugin that stores its data in an unconventional way. So review the list before deleting, don't delete everything the plugin calls orphaned in one go, and always take a backup first.
Because these two plugins are the most common, the difference between them deserves a closer look so you choose deliberately rather than at random. WP-Optimize follows an "all-in-one platform" philosophy: database cleanup + page caching + image compression in a single plugin, with a comfortable interface available in Arabic and clear buttons for each type of cleanup. Its strength is also its weakness: being comprehensive means you load a full caching engine and an image compression tool you may not want, just because you wanted to delete revisions. And if you use another caching plugin (many people do), running WP-Optimize's cache on top of it creates a conflict. A practical tip: if you choose it, disable its caching and image components in its settings and use it for cleanup only, and review its default schedule, because it may come more aggressive than you want.
Advanced Database Cleaner, on the other hand, is specialized rather than comprehensive: it's built mainly to detect what general tools don't see: orphaned data, tables left behind by deleted plugins, and orphaned cron jobs that stay scheduled for a plugin that no longer exists, draining every page load through WP-Cron. This is the last thing WP-Optimize detects, and it's this plugin's real strength. But its essential limit: its most powerful features, specifically orphaned table detection and classifying suspicious cron jobs, are largely reserved for the paid (Pro) version; the free version gives you basic row cleanup and limited table detection. And even with Pro, its "orphan" detection is a judgment call, not a certainty: it may flag a table as orphaned because its plugin is temporarily deactivated rather than deleted, so you delete it, then reactivate the plugin and it breaks. The rule: treat it as an excellent detection and diagnosis tool, not a reliable automatic deletion tool; let it flag the suspects for you, then judge each item yourself before deleting it.
The practical takeaway for choosing: if you want simple periodic cleanup of common rows (revisions, transients, spam) and you're fine with an all-in-one tool, WP-Optimize covers more ground. If you're specifically hunting for leftovers from deleted plugins (stray tables or orphaned cron jobs weighing down your site), Advanced Database Cleaner is the better detection tool, as long as you're aware that its greatest value sits behind the paid version's paywall. Either way, the most dangerous limit remains: no cleanup plugin knows your intentions; it executes its logic, not your judgment. A backup and a manual review before any bulk deletion remain your last line of defense, whatever the tool.
If you're building a new site and want a clean dashboard from the start, see the complete WordPress guide to set up sound foundations that reduce your need for cleanup later.
A practical maintenance plan, without overdoing it
The most common mistake after reading a guide like this is overdoing it: the site owner starts an obsessive daily cleanup and spends time chasing every surplus row while the site is fine. The truth is that the WordPress database is a resilient system that tolerates some bloat with no noticeable effect. A review every 3 to 6 months is perfectly sufficient for most sites, with one exception: watch autoload more closely if your site is getting heavier for no obvious reason.
A sensible plan looks like this: once a quarter, take a backup, run wp transient delete --expired, delete surplus revisions (after setting WP_POST_REVISIONS to stop them piling up), check autoload with the query above, and clean up spam. Then leave the site alone until the next quarter. There's no need for daily cleanup or for chasing every megabyte. Keep in mind that cleanup is part of broader maintenance that includes regular WordPress backups and sound caching, and the three together keep your site fast and secure.
Safeguards: non-negotiable rules
This is the most important section of the article, and I've deliberately left it near the end so you read it after understanding the tools. Every operation above is safe provided you follow these rules. Ignoring any one of them could cost you your entire site.
- A full, restorable backup before any operation. It isn't optional.
DELETEin phpMyAdmin can't be undone, and a mistake in aWHEREcondition wipes out years of content in a second. See the WordPress backup guide and make sure your backup actually restores, not just that it exists. - Test on staging first if you can. Try cleanup operations on an identical copy before production, especially deleting orphans and plugin tables. Most good hosts offer a one-click button to create a staging environment that clones your site along with its whole database. The safe workflow: create a staging site, run every delete statement you intend to run on production there, then actually browse the site: open posts, try a contact form, enter a sensitive plugin's dashboard, make sure your store displays products, before repeating the operations on production. This exposes "falsely orphaned" data before it hurts you: if a deletion breaks something, it breaks on the safe copy, not on your live site. A subtle note: don't copy the cleaned staging database over production thinking you've "merged" the work. A staging environment freezes the content at the moment it's created, so any request, comment or order that came in on production afterward would be lost if you replaced it. The right way is to rerun the verified statements directly on production, not to move the database.
- Always SELECT before DELETE. Preview what you're about to delete with a
SELECTstatement using the same condition before runningDELETE. A shocking number in the count = stop immediately. - Don't overdo it. A review every 3–6 months is enough. Obsessive daily cleanup creates more risks than it solves.
- Beware of "falsely orphaned" data. Some of what plugins (or your queries) call orphaned belongs to an active plugin that stores data in an unusual way. Verify before any bulk deletion.
- Deleting WooCommerce sessions wipes carts. If you run a store, cleaning up visitor sessions erases their unfinished carts. Clean them up with WooCommerce's dedicated tools, not by deleting at random from
wp_options. The detail matters here because it's a trap many people fall into: WooCommerce stores visitor sessions in its ownwp_woocommerce_sessionstable, not inwp_optionsas you might think, but it leaves traces inwp_optionsin the form of transient and session lock options (_transient_wc_session_*and similar). So when a general cleanup tool sees thousands of_transient_rows and offers to delete them all, it may wipe active sessions of visitors who are filling their carts right now, so their purchases disappear before checkout and you lose sales you'll never know about. That's why, on stores, don't run blind bulk transient deletion; use WooCommerce's own tool (Status > Tools > Clear customer sessions), which respects live sessions and deletes only expired ones. And if you must delete transients manually on a store, explicitly exclude everything starting with_transient_wc_session_from the deletion. - Don't delete categories/tags directly through phpMyAdmin. The taxonomy structure is spread across three related tables (
wp_terms,wp_term_taxonomy,wp_term_relationships); manually deleting a row from one of them breaks consistency. Delete them from the WordPress dashboard, which handles all three tables together.
Follow these rules, and cleanup turns from a scary operation into safe routine maintenance. Ignore them, and you may find yourself restoring a backup at best, or rebuilding your site from scratch at worst.
Frequently asked questions
Does cleaning up the WordPress database actually speed up the site?
Yes, but to varying degrees. The biggest effect comes from trimming bloated autoload options, because they are loaded on every page request for every visitor. Deleting revisions and transients reduces the database size and speeds up some queries, but the effect is less dramatic than autoload. OPTIMIZE TABLE on its own has a limited effect on speed, especially on the modern InnoDB engine.
What's the difference between this guide and the general database optimization guide? This guide is specific to WordPress: revisions, transients, autoload, orphaned data, maintenance done by the site owner. The general guide covers engine-level optimization for any database: indexing, tuning slow queries, MySQL server configuration, and object caching with Redis. The two complement each other, and neither replaces the other.
How many revisions does WordPress keep, and is deleting them safe?
WordPress saves a revision on every update and every autosave (every ~60s), so a single post can accumulate 50 revisions or more. Deleting them is relatively safe, but it's better to use WP-CLI (wp post delete ... --force) because it deletes the associated metadata along with them; deleting them with plain SQL leaves orphaned rows in wp_postmeta.
Why doesn't WordPress delete expired transients automatically?
Because the transient mechanism is "lazy": WordPress doesn't check all transients continuously (that would be costly); it only checks whether a transient has expired when it's requested. So if an expired transient is never requested again, it stays in wp_options forever. That's why cleaning them up manually, or on a schedule with wp transient delete --expired, is useful.
What's the ideal autoload size, and how do I find mine?
Aim to keep the total size of autoload options under about 800 KB to 1 MB. To find yours, run a SUM(LENGTH(option_value)) query with the condition WHERE autoload IN ('yes','on','auto','auto-on'). Note the use of IN rather than ='yes', because WordPress 6.6+ uses new values (on/auto) that the old query may miss.
Is OPTIMIZE TABLE necessary after every deletion? Not in any critical sense. On InnoDB (the modern default) its benefit is limited, and some fragmentation is normal. On MyISAM it does remove fragmentation, but it locks the table briefly. The real value lies in deleting surplus rows and trimming autoload, not in the optimize command itself. Treat it as an optional finishing touch after the actual cleanup.
Should I use a cleanup plugin or manual commands? If you're comfortable with WP-CLI or phpMyAdmin, the manual approach gives you more control and clearer visibility, and WP-CLI in particular is the cleanest because it deletes related data. If you're not, a plugin such as WP-Optimize is acceptable, provided you understand every option and avoid aggressive scheduling. Either way: a backup first, and a SELECT/preview before deleting.
Do wp-config constants delete existing revisions?
No. The WP_POST_REVISIONS constant (and its siblings) only stops future growth; it doesn't delete what already exists. If you already have thousands of revisions, delete them manually or with WP-CLI first, and the constant will then stop them from piling up again. The order: clean up, then set the constant as prevention.
What is "falsely orphaned" data and why is it a risk?
These are rows that appear to have no parent (for example, rows in wp_postmeta pointing to an ID that doesn't exist in wp_posts), but that actually belong to an active plugin that stores its data in an unconventional way or points to its own IDs. Deleting them in bulk can break the plugin. That's why you should review the list manually, never trust "orphan" detection blindly, and always take a backup.
Is deleting WooCommerce sessions safe?
Be careful: WooCommerce sessions store visitors' unfinished carts. Deleting them wipes those carts, and your visitors may lose their purchases before checkout. If you need to clean them up, use the WooCommerce tools designed for it (which respect session expiry), not random deletion from wp_options.
Sources
Frequently asked questions
Does cleaning up the WordPress database actually speed up the site?
Yes, but to varying degrees. The biggest effect comes from trimming bloated autoload options, because they are loaded on every page request for every visitor. Deleting revisions and transients reduces the database size and speeds up some queries, but the effect is less dramatic than autoload. OPTIMIZE TABLE on its own has a limited effect on speed, especially on the modern InnoDB engine.
What's the difference between this guide and the general database optimization guide?
This guide is specific to WordPress: revisions, transients, autoload, orphaned data, maintenance done by the site owner. The general guide covers engine-level optimization for any database: indexing, tuning slow queries, MySQL server configuration, and object caching with Redis. The two complement each other, and neither replaces the other.
How many revisions does WordPress keep, and is deleting them safe?
WordPress saves a revision on every update and every autosave (every ~60s), so a single post can accumulate 50 revisions or more. Deleting them is relatively safe, but it's better to use WP-CLI (wp post delete ... --force) because it deletes the associated metadata along with them; deleting them with plain SQL leaves orphaned rows in wp_postmeta.
Why doesn't WordPress delete expired transients automatically?
Because the transient mechanism is "lazy": WordPress doesn't check all transients continuously (that would be costly); it only checks whether a transient has expired when it's requested. So if an expired transient is never requested again, it stays in wp_options forever. That's why cleaning them up manually, or on a schedule with wp transient delete --expired, is useful.
What's the ideal autoload size, and how do I find mine?
Aim to keep the total size of autoload options under about 800 KB to 1 MB. To find yours, run a SUM(LENGTH(option_value)) query with the condition WHERE autoload IN ('yes','on','auto','auto-on'). Note the use of IN rather than ='yes', because WordPress 6.6+ uses new values (on/auto) that the old query may miss.
Is OPTIMIZE TABLE necessary after every deletion?
Not in any critical sense. On InnoDB (the modern default) its benefit is limited, and some fragmentation is normal. On MyISAM it does remove fragmentation, but it locks the table briefly. The real value lies in deleting surplus rows and trimming autoload, not in the optimize command itself. Treat it as an optional finishing touch after the actual cleanup.
Should I use a cleanup plugin or manual commands?
If you're comfortable with WP-CLI or phpMyAdmin, the manual approach gives you more control and clearer visibility, and WP-CLI in particular is the cleanest because it deletes related data. If you're not, a plugin such as WP-Optimize is acceptable, provided you understand every option and avoid aggressive scheduling. Either way: a backup first, and a SELECT/preview before deleting.
Do wp-config constants delete existing revisions?
No. The WP_POST_REVISIONS constant (and its siblings) only stops future growth; it doesn't delete what already exists. If you already have thousands of revisions, delete them manually or with WP-CLI first, and the constant will then stop them from piling up again. The order: clean up, then set the constant as prevention.
What is "falsely orphaned" data and why is it a risk?
These are rows that appear to have no parent (for example, rows in wp_postmeta pointing to an ID that doesn't exist in wp_posts), but that actually belong to an active plugin that stores its data in an unconventional way or points to its own IDs. Deleting them in bulk can break the plugin. That's why you should review the list manually, never trust "orphan" detection blindly, and always take a backup.
Is deleting WooCommerce sessions safe?
Be careful: WooCommerce sessions store visitors' unfinished carts. Deleting them wipes those carts, and your visitors may lose their purchases before checkout. If you need to clean them up, use the WooCommerce tools designed for it (which respect session expiry), not random deletion from wp_options.