This guide walks you through safely cleaning and maintaining your WordPress database tables. You’ll learn how to remove orphaned data, optimize table performance, and set up a routine that keeps your site fast without risking data loss. Before you start, you need a full backup of your database and access to phpMyAdmin or a similar database management tool.
What You’ll Need
- A full database backup (use a plugin like UpdraftPlus or your host’s backup tool)
- Access to phpMyAdmin, Adminer, or your hosting control panel’s database manager
- FTP or file manager access (only if you need to edit wp-config.php)
- A staging site (recommended) or a low-traffic window to work in
Step-by-Step
- Create a complete backup. Go to your backup plugin or hosting panel and export both the database and all files. Store the backup offsite (e.g., Google Drive, Dropbox). Verify the backup file is non-zero and downloadable before proceeding.
- Log into phpMyAdmin. In your hosting control panel, find the database management section. Select your WordPress database (usually named something like
youruser_wp). - Check the table prefix. Look at the table names. Most WordPress installs use
wp_as the prefix (e.g.,wp_posts,wp_options). If you see tables with different prefixes, note them—you’ll need to adjust the SQL queries below. - Run the OPTIMIZE command on all tables. In phpMyAdmin, click the “Check All” checkbox at the bottom of the table list, then select “Optimize” from the “With selected:” dropdown. This defragments InnoDB tables and reclaims unused space. It’s safe and non-destructive.
- Delete transients (cached data). Transients are temporary options stored in the
wp_optionstable. Run this SQL query (replacewp_with your prefix):DELETE FROM wp_options WHERE option_name LIKE '_transient_%' OR option_name LIKE '_site_transient_%';
This removes expired and stale cached data. It’s safe—WordPress will regenerate what it needs.
- Clean up post revisions. Revisions bloat the
wp_poststable. Keep only the latest revision for each post with this query:DELETE FROM wp_posts WHERE post_type = 'revision' AND ID NOT IN (SELECT MAX(ID) FROM wp_posts WHERE post_type = 'revision' GROUP BY post_parent);
If you want to limit to, say, the last 5 revisions per post, use a plugin instead (e.g., WP-Optimize) to avoid complex SQL.
- Remove orphaned postmeta. After deleting revisions, some
wp_postmetarows may point to non-existent posts. Run:DELETE pm FROM wp_postmeta pm LEFT JOIN wp_posts p ON p.ID = pm.post_id WHERE p.ID IS NULL;
This removes metadata for deleted posts, comments, and terms.
- Clean up orphaned term relationships. Run these two queries to remove term relationships for deleted posts and terms:
DELETE tr FROM wp_term_relationships tr LEFT JOIN wp_posts p ON p.ID = tr.object_id WHERE p.ID IS NULL; DELETE tr FROM wp_term_relationships tr LEFT JOIN wp_term_taxonomy tt ON tt.term_taxonomy_id = tr.term_taxonomy_id WHERE tt.term_taxonomy_id IS NULL;
These are safe—they only remove rows that reference missing data.
- Check for unused tables. Look for tables that are not part of a standard WordPress install (e.g.,
wp_commentmetais standard, butwp_myplugin_datamay be from a plugin you’ve deleted). If you’re sure a plugin is gone and its tables remain, you can drop them—but only if you have a backup and are certain they aren’t used by another plugin. - Optimize again. After the deletions, run the OPTIMIZE command again to physically shrink the table files.
- Verify your site. Load your homepage, a post, and the admin dashboard. Check for errors. If something breaks, restore from backup.
- Set a maintenance schedule. Do this monthly. You can use a plugin like WP-Optimize or Advanced Database Cleaner to automate these steps, or set a calendar reminder to do it manually.
Common Mistakes
- Skipping the backup. The #1 mistake. One wrong query can wipe your content.
- Deleting all transients without testing. While generally safe, some plugins store non-expiring transients that are needed. If your site breaks, restore the backup.
- Running queries on the wrong database. Double-check you’ve selected the correct database in phpMyAdmin before running any SQL.
- Deleting tables without knowing what they are. A plugin might still be active but its tables are hidden from the plugin list. Always cross-reference.
- Using the wrong table prefix. If your prefix is
wp2_, usingwp_in queries will fail or affect nothing. - Over-optimizing too frequently. Daily optimization can cause table locks and actually slow down a busy site. Monthly is enough.
Tips
- Use a staging site to test all SQL queries before running them on production.
- Export a fresh backup right before each maintenance session, not just the first time.
- Consider disabling pingbacks and trackbacks—they create a lot of junk in
wp_comments. - Limit post revisions by adding to
wp-config.php:define('WP_POST_REVISIONS', 5);or set it tofalseto disable revisions entirely. - Use a caching plugin to reduce database load, which means less junk accumulates.
- If you’re not comfortable with SQL, use a reputable plugin like WP-Optimize—it does the same thing with a UI.
Troubleshooting
- Site shows “Error establishing a database connection” after cleanup. This usually means you deleted a critical table or row. Restore your backup immediately. If you didn’t delete anything, check that your database user still has proper privileges.
- Queries return no results or errors. Check your table prefix. Run
SHOW TABLES;to see the exact names. Also ensure you’re using the correct database—phpMyAdmin sometimes defaults to a different one. - Site loads but some pages are broken. A plugin might rely on data you deleted (e.g., transients that store API responses). Clear your site cache and try again. If the issue persists, restore the backup and investigate which query caused it.
- Optimize takes forever or times out. On large databases, optimization can be slow. Use phpMyAdmin’s “Optimize” button instead of running a huge SQL query, or do it during off-peak hours. If it times out, increase PHP’s max execution time in
php.inior use a plugin that processes tables in batches. - Database size didn’t shrink much. If you’re using InnoDB, the size may not decrease until you optimize. Also, if you have lots of content, the size is normal. Check for large tables like
wp_logsfrom security plugins—those can be cleaned separately.
Frequently Asked Questions
Is it safe to delete all transients?
Yes, but with caution. Transients are temporary cached data. Deleting them forces WordPress to regenerate them, which is fine. However, if a plugin stores non-expiring data as a transient (rare but possible), that data will be lost. Test after deletion.
How often should I clean my WordPress database?
Monthly is a good baseline. If your site has heavy comment traffic or many post revisions, you may want to do it every two weeks. Daily is unnecessary and can cause performance issues.
Can I clean the database without phpMyAdmin?
Yes, you can use plugins like WP-Optimize, Advanced Database Cleaner, or WP-Sweep. These provide a UI and automate the process. However, they still require a backup and should be tested.
Will cleaning the database speed up my site?
It can, especially if the database is bloated with revisions, transients, and orphaned data. However, if your site is slow due to hosting or unoptimized images, database cleanup won’t fix that. It’s one piece of the puzzle.
What is the difference between OPTIMIZE and REPAIR?
OPTIMIZE defragments the table and reclaims unused space. REPAIR fixes corrupted tables. You should only run REPAIR if you see errors about table corruption. Regular maintenance uses OPTIMIZE.
Do I need to clean the database if I use a caching plugin?
Yes. Caching plugins reduce database queries, but they don’t remove orphaned data or revisions. Database cleanup is still necessary for long-term health.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Philips DST7060/20 7000 Series Iron: Specs & Fit
- Coal Fueled Jet Aircraft: Could It Work?675 L
- Remote Desktop on Raspberry Pi: How to Enable It
- Word Select Last Line in Paragraph?
- Google Assistant IFTTT Recipes: 7 Useful Automations
- OLED TVs in Dark Rooms: Why They Look Better and When They Don’t