Database Optimization Tips for Definitive WordPress Sites
Database bloat slows WordPress to a crawl. Learn proven optimization techniques—cleaning tables, indexing queries, and leveraging caching—to reclaim speed. At HostWP, we've seen 40% performance gains after optimization. Start today with our free audit.
Key Takeaways
- Clean up post revisions, trashed items, and spam comments—they bloat your database and slow queries by up to 30%
- Proper indexing on wp_postmeta and wp_posts tables combined with Redis caching can cut database response time in half
- Regular maintenance—weekly cleanups, monthly optimizations—prevents database creep that degrades performance over time
Database optimization is the invisible engine of WordPress speed. While most site owners focus on caching plugins and CDNs, they overlook the fact that a bloated database forces your server to work harder on every request—whether cached or not. At HostWP, we've migrated and audited over 500 South African WordPress sites, and we consistently find that 67% have databases ballooning with unnecessary revisions, metadata, and transient data. This isn't just a performance issue; it directly impacts your bottom line. A slow site converts fewer visitors, ranks lower on Google, and costs you more in hosting resources. This guide gives you the exact steps to audit, clean, and optimize your database—with real numbers showing what to expect.
I've spent the last five years managing WordPress infrastructure across South Africa's fibre networks (Openserve, Vumatel) and LiteSpeed servers. Database optimization isn't a one-time task; it's foundational to keeping your site fast regardless of traffic spikes or load shedding disruptions. Let's dive into what actually works.
In This Article
Audit Your Database: Know What You're Carrying
Before you optimize, you need to understand your current state. Most WordPress sites run on MySQL (or MariaDB on newer servers like ours at HostWP), and phpMyAdmin gives you direct visibility into what's eating space and slowing queries. Run this simple query to check your database size:
SELECT table_name, (data_length + index_length) / 1024 / 1024 AS size_mb FROM information_schema.tables WHERE table_schema = 'your_database_name' ORDER BY (data_length + index_length) DESC;
This shows you every table ranked by size. On typical SA WordPress sites we audit, the wp_posts, wp_postmeta, and wp_comments tables consume 60–75% of total database size. In one case, a Cape Town agency's site had a 850 MB database; after cleanup, it dropped to 240 MB—a 72% reduction that cut query response time from 1,200 ms to 380 ms. That's the difference between a crawling site and one that feels instant.
Document three metrics: total database size, largest table, and table count. If you're on a shared hosting plan elsewhere (say, Xneelo or Afrihost), check your hosting control panel for current database size. On HostWP's plans, starting from R399/month, you get direct access to this data, daily backups, and our 24/7 support team can run these audits for you.
Asif, Head of Infrastructure at HostWP: "In our experience, WordPress sites under three years old average 180 MB databases; sites five years or older sit at 560 MB. The difference isn't traffic—it's unmanaged post revisions and orphaned metadata. We've seen sites where a single post had 1,247 revisions. That's not a feature; that's bloat."
Clean Out the Bloat: Post Revisions, Transients, and Spam
Post revisions are WordPress's version control feature—every time you save a draft, a new revision is created. By default, WordPress keeps unlimited revisions. On a busy blog or news site, a single post can accumulate dozens of revisions. A Johannesburg e-commerce client we migrated had 42,000 post revisions across 1,200 posts—accounting for 89 MB of database bloat alone.
Limit future revisions by adding this to wp-config.php:
define('WP_POST_REVISIONS', 3);
This keeps the last 3 revisions per post—enough for recovery, minimal bloat. To clean existing revisions, use this SQL query:
DELETE FROM wp_posts WHERE post_type = 'revision';
Next, clean spam comments and spam meta. Spammers create thousands of comment rows, and each failed spam check leaves traces. Run:
DELETE FROM wp_comments WHERE comment_approved = 'spam';
DELETE FROM wp_commentmeta WHERE comment_id NOT IN (SELECT comment_ID FROM wp_comments);
On a Durban fitness site we serviced, this freed up 12 MB. Transients—temporary cached data in wp_options—accumulate over time. Expired transients clog your database without serving any purpose:
DELETE FROM wp_options WHERE option_name LIKE '%_transient_%' AND option_name NOT LIKE '%_transient_timeout_%';
A final crucial step: remove orphaned postmeta (metadata attached to deleted posts). This is invisible to WordPress but drags on every query:
DELETE FROM wp_postmeta WHERE post_id NOT IN (SELECT ID FROM wp_posts);
Database cleanup is powerful—but risky without backups. HostWP includes automated daily backups and point-in-time recovery on all plans. If you're running database optimizations for the first time, we offer a free WordPress audit and can handle cleanup safely for you.
Get a free WordPress audit →Indexing for Speed: Make Queries Sing
Indexing is how databases avoid full table scans. Without indexes, MySQL reads every single row to find what you need—imagine scanning every page of a 500-page book to find a name instead of using the index. WordPress creates some indexes by default, but custom plugins and heavy postmeta usage often outpace them.
Check which tables lack indexes:
SELECT table_name, column_name FROM information_schema.statistics WHERE table_schema = 'your_database' GROUP BY table_name, column_name ORDER BY table_name;
The wp_postmeta table especially benefits from indexing. If you're running WooCommerce or a custom post type with heavy metadata, add these indexes:
ALTER TABLE wp_postmeta ADD INDEX meta_key_postid (meta_key, post_id);
ALTER TABLE wp_postmeta ADD INDEX post_id (post_id);
We implemented this on a Johannesburg WooCommerce store with 8,000 products. Search queries that took 850 ms dropped to 120 ms. That's not marginal—that's the difference between a customer leaving due to slowness and completing a purchase.
For wp_posts, ensure you have indexes on post_name, post_author, and post_date:
ALTER TABLE wp_posts ADD INDEX post_author (post_author);
ALTER TABLE wp_posts ADD INDEX post_name (post_name);
On HostWP's LiteSpeed-powered servers, combined with Redis caching, these indexes can reduce your average query time by 45–60%. Don't add indexes blindly, though—every index slows write operations. Focus on tables you query frequently, identified in your site's slow query log.
Caching Strategies: Redis and Query Optimization
A clean, indexed database is the foundation. But even optimized queries are slower than cached results. Redis—an in-memory data store—is the gold standard for WordPress performance. Every HostWP plan includes Redis standard, which means your most-run queries live in RAM, not on disk.
Redis sits between WordPress and your database, intercepting repeated queries. A typical WordPress homepage query runs 80–120 database calls. Without caching, those hit disk every time. With Redis, 75–90% of queries return from memory in under 2 ms instead of 50–200 ms on disk.
Enable Redis caching in your plugin stack. WP Super Cache and W3 Total Cache both support Redis. We recommend WP Super Cache for simplicity on single-site installations, or LiteSpeed Cache if you're on LiteSpeed (which you are on HostWP):
Settings → LiteSpeed Cache → Object → Object Cache: Redis
Configure your Redis connection (HostWP's support team provides this)—typically localhost:6379—and flush the cache after setup. Now monitor your admin panel. After one week, check Site Health and Performance. You should see database query counts drop by 60% and average page load time fall 1–2 seconds on most pages.
Beyond caching, optimize your queries themselves. Use WP-CLI to audit slow queries:
wp db query --skip-column-names "SELECT SQL_TEXT, COUNT FROM mysql.slow_log LIMIT 10;"
Identify the slowest 10 queries, check if they're using indexes, and if not, apply indexing or filter your WP_Query arguments to reduce result sets. On a Pretoria news site, reducing WP_Query's posts_per_page and adding proper taxonomies cut load time by 2.3 seconds.
Scheduled Maintenance: Keep It Lean
Optimization isn't a one-time event. Databases grow continuously—new posts, comments, plugin data. Without maintenance, you'll return to bloat within 3–6 months. Automate weekly and monthly tasks.
Weekly: Clean spam and pending comments
DELETE FROM wp_comments WHERE comment_approved = 'spam';
DELETE FROM wp_comments WHERE comment_approved = '0' AND comment_date_gmt < DATE_SUB(NOW(), INTERVAL 30 DAY);
Monthly: Optimize all tables
OPTIMIZE TABLE wp_posts, wp_postmeta, wp_comments, wp_commentmeta, wp_options;
OPTIMIZE TABLE defrags your tables, reclaiming unused space. On larger databases, run this during off-peak hours to avoid locking tables during customer browsing. South Africa's evening hours (20:00–22:00 SAST) typically see lowest traffic.
For ongoing monitoring, install a maintenance plugin like Advanced Database Cleaner or WP Optimize. Schedule them to run weekly. These plugins can automate revision cleanup, transient deletion, and table optimization, removing the manual work.
At HostWP, load shedding sometimes forces unplanned downtime. Before any maintenance window—especially database work—ensure you have a recent backup. Our daily backup system captures your entire database and files, accessible for instant restore if any optimization goes sideways.
Monitor and Measure: Track Real Gains
You've cleaned your database, added indexes, and enabled Redis. Now measure the impact. Use these tools to quantify improvements:
1. Query Time: Enable WordPress debug logging
Add to wp-config.php:
define('SAVEQUERIES', true);
Then check $wpdb->queries in your theme's footer template. Average query time should drop from 40–80 ms (pre-optimization) to 8–15 ms (post-optimization) on cached pages, and 15–30 ms on uncached.
2. Page Load Time: Use Google PageSpeed Insights or WebPageTest
Run a full site audit before optimization, then re-run weekly. On average, SA sites see 1.5–3 second improvements in First Contentful Paint after database optimization, depending on site size and hosting tier.
3. Database Size: Track in phpMyAdmin
Document size monthly. A healthy WordPress site grows 2–4% monthly (new posts, comments). If growth exceeds 8%, you have orphaned data or a plugin creating junk.
We tracked a Cape Town marketing agency's site over four months: Week 0 (baseline: 520 MB), Week 2 (post-cleanup: 180 MB), Week 8 (with Redis: 1.2 sec load time), Week 16 (with indexing and ongoing maintenance: 0.8 sec). That's a 33% improvement in load time and a 65% reduction in database size. Better yet, the client's hosting costs dropped from R2,400/month to R899/month because the site used fewer resources.
Create a simple spreadsheet tracking: database size, query count per page, average query time, and page load time. Review monthly. If metrics stagnate or regress, revisit your cleanup and caching configuration. Database optimization compounds—the longer you maintain it, the better your baseline becomes.
Frequently Asked Questions
Q: Will database optimization break my WordPress site?
A: Only if you skip backups. Every query we've discussed is destructive—it deletes data. Always back up before running database operations. HostWP's daily backups mean you can restore instantly if anything goes wrong. If you're unsure, ask our 24/7 support team to run optimization for you.
Q: How often should I optimize my database?
A: Weekly for cleanup (spam, transients), monthly for OPTIMIZE TABLE. Indexing is a one-time task unless you add new custom post types or plugins. With automation via plugins, you'll spend zero manual time and see consistent 10–15% performance gains quarterly.
Q: Does Redis caching use extra disk space?
A: No, Redis runs in RAM, not on disk. It stores temporary copies of query results in memory. On HostWP, Redis is included and managed—you don't pay extra per MB cached. Typical overhead is 20–50 MB of RAM per site depending on traffic.
Q: Can I optimize a database while my site is live?
A: Yes, with caution. Run DELETE queries during low-traffic windows (midnight–6 AM SAST is safest). OPTIMIZE TABLE locks the table briefly (5–30 seconds depending on size), so schedule it off-peak. Always notify your team before running production changes.
Q: My database is 2 GB. Will optimization fix a slow site?
A: Likely, but size alone isn't always the issue—structure is. A 2 GB database that's clean and indexed performs better than a 500 MB database that's bloated. Run the audit queries first. If your largest tables are properly indexed and your caching is active, a slow site might be a plugin issue, not the database. Our free audit identifies the real bottleneck.