Skip to content
Back to Blog
WordPress11 min read

7 WordPress Database Optimization Mistakes That Break Sites

Running OPTIMIZE TABLE during peak traffic or blindly deleting revisions can lock tables and crash your site. Learn the safe way to tune your WordPress database without downtime.

Written by Abdul AbrorTechnical Hosting Support Engineer
7 WordPress Database Optimization Mistakes That Break Sites
On this page

Your WordPress site is slow, so you Google "database optimization" and follow the first tutorial you find. Twenty minutes later the site is down, tables are locked, and you're staring at a database connection error. I've restored backups for dozens of clients who thought they were making their site faster.

Database optimization is powerful but unforgiving. One wrong query during business hours can lock tables for minutes, drop critical data, or corrupt indexes. The techniques themselves work fine—it's the timing, order, and scope that break production sites.

Running OPTIMIZE TABLE during peak traffic

This is the mistake I see most. Someone schedules a cron job to run OPTIMIZE TABLE on all tables at 2 PM when the site has hundreds of active users.

OPTIMIZE TABLE in MySQL (and MariaDB with InnoDB) completely rebuilds the table. It locks the table for writes and sometimes reads depending on your storage engine. On a table with millions of rows, that can take 5-15 minutes. Every write query waits. Pages time out. Checkout processes fail.

The correct approach: run maintenance during your traffic valley, usually 2-4 AM in your primary timezone. Check your analytics for the actual low point. If you're on shared hosting and can't pick the exact minute, at least avoid business hours.

Better still, use pt-online-schema-change from Percona Toolkit for large tables. It copies data to a shadow table and swaps atomically, so writes keep flowing. The command looks like this:

pt-online-schema-change --alter "ENGINE=InnoDB" \
  D=your_database,t=wp_posts \
  --execute

For InnoDB tables under 100 MB, the built-in OPTIMIZE is usually fast enough if timed right. For anything bigger or mission-critical, use the online method.

Deleting all post revisions in a single query

WordPress saves every draft edit as a revision. A three-year-old site might have 50,000 revision rows in wp_posts. Someone finds a snippet that deletes them all:

DELETE FROM wp_posts WHERE post_type = 'revision';

This query locks wp_posts for the entire duration. Depending on server specs, deleting 50,000 rows can take 30 seconds to two minutes. Every page load that queries posts waits. The site effectively freezes.

The safe method is to delete in small batches with a delay between each:

DELETE FROM wp_posts WHERE post_type = 'revision' LIMIT 500;

Run that in a loop with a one-second sleep. You can script it in WP-CLI:

while [ $(wp db query "SELECT COUNT(*) FROM wp_posts WHERE post_type='revision'" --skip-column-names) -gt 0 ]; do
  wp db query "DELETE FROM wp_posts WHERE post_type='revision' LIMIT 500"
  sleep 1
done

Each batch takes a fraction of a second, releases the lock, and lets normal traffic through. The whole cleanup might take five minutes instead of 30 seconds, but your site stays up.

Skipping backups before running cleanup queries

You're confident the query is safe. You tested it on staging. You run it on production and realize two seconds later you targeted the wrong table or forgot a WHERE clause.

In support tickets I handled, the usual culprit was a typo in the table prefix. Someone assumed wp_ but the site used wpdb_. The query deleted live posts instead of orphaned metadata.

Always take a fresh backup right before database maintenance, even if you have nightly backups. A restoration from ten minutes ago loses ten minutes of data. A restoration from last night loses a full day of orders, comments, and content.

For cPanel users, the easiest path is a manual backup in phpMyAdmin (export as SQL) or via command line:

mysqldump -u username -p database_name > backup_$(date +%F_%H-%M).sql

Keep that file outside the web root until you've verified the optimization worked. If something breaks, you can restore in under a minute instead of spending an hour diagnosing what went wrong.

Using plugins that auto-optimize every hour

Some optimization plugins offer a "run automatically" option that fires every hour or after every post update. Sounds convenient, but it's a resource trap.

Optimizing tables isn't free. Even a quick ANALYZE TABLE reads index statistics and can cause brief locks. Doing it every hour on a busy site means you're constantly adding load during traffic peaks.

WordPress core handles query caching and object caching well enough that most sites don't benefit from hourly table optimizations. The performance gain is marginal—maybe 10-20 ms on a slow query—but the risk of a lock during a sale or launch is real.

Schedule optimization once a week or once a month depending on write volume. A news site publishing 50 posts a day might benefit from weekly maintenance. A brochure site with one post a month can do quarterly cleanups.

If you insist on automation, schedule it for 3 AM on a Tuesday (statistically the lowest traffic window for most sites). Disable the "optimize on every post save" triggers entirely.

Dropping indexes without understanding query patterns

Someone reads that "too many indexes slow down writes" and decides to drop every index except the primary key. Suddenly every query scans the full table and the site grinds to a halt.

Indexes do slow writes slightly—each INSERT or UPDATE has to maintain the index structure—but the read speedup is usually worth it. Dropping an index on post_status means WordPress has to scan every row in wp_posts to find published posts. On a 100,000-row table that can turn a 5 ms query into a 500 ms query.

Before dropping an index, check if queries actually use it. Enable the slow query log in MySQL:

slow_query_log = 1
long_query_time = 1
slow_query_log_file = /var/log/mysql/slow.log

Let it run for 24 hours. Analyze the output with pt-query-digest or manually review the log. If you see Using where; Using filesort on a query that hits wp_postmeta, that's a sign the index isn't helping—or is missing entirely.

Only drop indexes that never appear in EXPLAIN output and aren't part of a foreign key constraint. Even then, test on staging first and monitor query times for a week before calling it done.

Converting tables to MyISAM for "speed"

An old tutorial says MyISAM is faster than InnoDB, so someone converts all tables:

ALTER TABLE wp_posts ENGINE=MyISAM;

MyISAM does have faster reads in very specific scenarios—single-threaded, read-heavy workloads with no transactions. But WordPress is write-heavy. Every comment, every post save, every plugin settings update is a write. MyISAM locks the entire table for writes. One slow INSERT blocks every other write and every read.

Worse, MyISAM has no transaction support and no crash recovery. If MySQL crashes mid-write, the table can corrupt. I've seen wp_options and wp_postmeta corrupted beyond repair after a server reboot during a MyISAM conversion.

Stick with InnoDB. It's the default for WordPress since 5.0 and handles concurrent writes far better. Row-level locking means a comment insertion doesn't block a post query. Transaction support means atomic updates—either the whole operation succeeds or none of it does.

If you've inherited a site with MyISAM tables, convert them back:

ALTER TABLE wp_posts ENGINE=InnoDB;

Do it during low traffic with a backup ready, because the conversion itself locks the table.

Ignoring foreign key constraints in multisite

WordPress multisite uses shared tables (wp_users, wp_usermeta) and per-site tables (wp_2_posts, wp_3_posts). If you delete a user from wp_users without cleaning up their posts in every subsite, you leave orphaned rows.

Someone runs a cleanup script that deletes inactive users from the main users table. Now 15 subsites have posts with post_author values that don't exist. Trying to display the author name throws errors or shows blank fields.

MySQL foreign key constraints would catch this, but WordPress doesn't use them by default because they weren't supported in older MyISAM setups. You have to enforce referential integrity manually.

Before deleting users, check for their content across all sites:

SELECT blog_id, COUNT(*) 
FROM wp_2_posts 
WHERE post_author = 123 
GROUP BY blog_id;

Reassign their posts to a placeholder user (ID 1 is usually the network admin) or delete the posts explicitly. Never assume deleting the parent record cascades.

The same applies to term relationships. Deleting a term from wp_terms without cleaning wp_term_relationships leaves orphaned links. WordPress usually handles this through its API (wp_delete_term), but direct SQL bypasses those safeguards.

What to check first

Run SHOW TABLE STATUS and look at the Data_free column. That's how much space InnoDB is wasting on deleted rows. If it's under 10% of the total table size, optimization won't gain much. If it's over 30%, you'll see real space savings—but still schedule it for low traffic.

Check your slow query log. If you don't have queries over 1 second, your database isn't the bottleneck. Optimizing tables won't fix a slow theme or unoptimized images.

Test every destructive query on a staging copy first. Export a recent backup, restore it locally or on a staging subdomain, and run your cleanup there. Verify the result with SELECT queries before touching production.

Database optimization is maintenance, not a one-time fix. Schedule it quarterly, automate backups, and never run it blind during business hours.

How often should I optimize WordPress tables?

Once a month for high-traffic sites, quarterly for low-traffic ones. More frequent optimization doesn't improve performance and adds unnecessary load.

Can I optimize tables on shared hosting?

Yes, but you're limited by resource caps. Most shared hosts kill long-running queries after 30-60 seconds. Optimize one table at a time and avoid peak hours.

Will optimization reduce my database size?

It depends. If you've deleted thousands of rows, OPTIMIZE TABLE reclaims that space. If your tables are actively growing, it might shrink them 5-10% at most.

Is it safe to delete transients?

Yes, expired transients are safe to delete. WordPress clears them automatically, but some accumulate if a plugin misbehaves. Delete only transients with an expiration timestamp in the past.

What if OPTIMIZE TABLE times out?

Split large tables by deleting old data first (spam comments, trashed posts) to reduce row count, then optimize. Or use pt-online-schema-change for zero-downtime optimization.

Run a test optimization first

Pick your smallest table—usually wp_options—and optimize it manually during a known low-traffic window. Watch your error logs and server load. Time how long it takes. If that works cleanly, move to the next table.

Never optimize all tables in one command until you've confirmed each one individually. One bad table can cascade into a full site outage, and isolating the problem is easier when you've changed one thing at a time.