How to optimize the WordPress database?

How to optimize the WordPress database?

Last verified: November 21, 2026
8 min read
Guide

Expanded and up-to-date version of this topic: WordPress database optimization in 2026: Cleaning up the bloat.

WordPress stores everything in a MySQL (or MariaDB) database. Over time, this database “bloats”, accumulating unnecessary data, which can slow down queries and the entire site. A larger database means longer backup times, slower SELECT queries, and increased Time To First Byte (TTFB).

In this comprehensive guide for developers, I will go through advanced database optimization, from simple cleaning to query analysis and InnoDB configuration.


#Why does WordPress database speed matter?

In 2026, when a TTFB under 100ms is the standard, a “heavy” database is an anchor for your site. Even if you have a super-fast server (PHP 8.4, NVMe), poorly optimized SQL queries can kill performance.

#What makes a WordPress database slow

  1. Bloatware (Excess Data): Post revisions, comment spam, orphaned metadata.
  2. Autoloaded Options: Data loaded on every page refresh, even if unused.
  3. Missing Indexes: Queries that must scan the entire table (Full Table Scan).
  4. Table Fragmentation: Gaps in data that increase file size on disk.

#How to clean the WordPress database

Let’s start by removing the trash. You can do this with a plugin (WP-Optimize), but as a developer, you should know how to do it “manually” using SQL or WP-CLI.

#How to delete post revisions

Every time you click “Save Draft”, a new copy of the post is created. With long editing sessions, you can have hundreds of revisions for a single article.

SQL Query to Check Revision Count:

SELECT COUNT(*) FROM wp_posts WHERE post_type = 'revision';

Deleting Revisions (SQL):

DELETE FROM wp_posts WHERE post_type = 'revision';

Recommended: Use WP-CLI (Safer):

wp post delete $(wp post list --post_type='revision' --format=ids) --force

#How to delete spam and trashed comments

There is no point in keeping spam or deleted posts.

SQL:

DELETE FROM wp_comments WHERE comment_approved = 'spam';
DELETE FROM wp_comments WHERE comment_approved = 'trash';

#How to delete expired transients

Transients are cache saved in the database (wp_options). Sometimes expired transients are not automatically removed.

SQL Cleaning Expired Transients:

DELETE FROM wp_options WHERE option_name LIKE ('_transient_timeout%') OR option_name LIKE ('_transient_%');

WP-CLI (Best Method):

wp transient delete --all

#How to reduce autoloaded options in wp_options

The wp_options table contains an autoload column. If set to yes, that option is loaded on every page load. Plugins often leave trash here after uninstallation.

#How to check autoload size in MySQL

Check how much data (in bytes) is being autoloaded:

SELECT SUM(LENGTH(option_value)) as autoload_size FROM wp_options WHERE autoload = 'yes';

If the result exceeds 800 KB - 1 MB, you have a problem.

#How to find the largest autoloaded options

SELECT option_name, LENGTH(option_value) as option_size
FROM wp_options
WHERE autoload = 'yes'
ORDER BY option_size DESC
LIMIT 10;

You will often find old data from cache plugins, builders, or logs here. If the plugin is no longer used, you can safely delete these options or change autoload to no.


#How to convert MyISAM tables to InnoDB

In 2026, you should no longer use the MyISAM engine. InnoDB is the standard, offering:

  • Row-level locking: MyISAM locks the entire table on write.
  • ACID Transactions: Data safety.
  • Foreign Keys: Relationship consistency.

#How to check which engine your tables use

SELECT TABLE_NAME, ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'your_database_name';

#How to change the table engine with ALTER TABLE

If you find MyISAM tables, convert them:

ALTER TABLE wp_posts ENGINE=InnoDB;
ALTER TABLE wp_comments ENGINE=InnoDB;
ALTER TABLE wp_options ENGINE=InnoDB;
-- and so on for all tables

#How to index MySQL tables for WordPress speed

WordPress usually has good default indexes, but plugins often add their own tables without proper indexes. Missing an index on a WHERE or JOIN query means MySQL must scan every row in the table.

#Why is WooCommerce order search slow?

If you have a store with 100,000 orders, and a plugin searches orders by meta_key without an index, the “My Account” page might take 10 seconds to load.

Solution: Add indexes to columns you frequently search or sort by.

CREATE INDEX idx_meta_key_value ON wp_postmeta (meta_key(191), meta_value(50));

(Note: Indexing meta_value is tricky because it’s TEXT. Avoid searching by meta_value if possible).


#How to stop database bloat with wp-config?

Instead of constantly cleaning, it’s better not to litter. Configure WordPress wisely.

#How to limit post revisions and autosave?

Add to wp-config.php:

// Limit to 5 recent versions
define( 'WP_POST_REVISIONS', 5 );

// Empty trash every 7 days (default is 30)
define( 'EMPTY_TRASH_DAYS', 7 );

// Increase autosave interval (fewer AJAX requests in editor)
define( 'AUTOSAVE_INTERVAL', 300 ); // seconds

#How to disable the WordPress file editor

For security and hygiene:

define( 'DISALLOW_FILE_EDIT', true );

#How to find slow queries with Query Monitor

Don’t guess what slows down the site. Install the Query Monitor plugin. After installation, in the admin bar, you will see page generation time and number of SQL queries.

  1. Click on statistics in the bar.
  2. Go to the “Queries” tab.
  3. Sort by “Time”.

If you see a query taking 0.5s or more, that’s your optimization target. It often comes from a poorly written plugin (“Recently Viewed Products”, “Visit Counter”, etc.).


#How to automate WordPress database maintenance with WP-CLI

Manual cleanup does not scale once you manage multiple stores or editorial sites.

#Weekly maintenance script with WP-CLI

#!/bin/bash
wp transient delete --expired
wp comment delete $(wp comment list --status=spam --format=ids) --force 2>/dev/null
wp comment delete $(wp comment list --status=trash --format=ids) --force 2>/dev/null
wp db optimize
wp db size --tables

Schedule it with cron on staging first, then production after you confirm no coupon or session plugins rely on short-lived transients.

#Orphaned metadata in wp_postmeta

When posts are deleted without cascading metadata, wp_postmeta rows remain:

DELETE pm FROM wp_postmeta pm
LEFT JOIN wp_posts wp ON wp.ID = pm.post_id
WHERE wp.ID IS NULL;

Run this only after a backup. On WooCommerce shops, verify the orphan rows are not tied to scheduled actions still referenced by Action Scheduler.


#UK and Ireland law when exporting WordPress database dumps

Staging copies of wp_users, wp_woocommerce_order_items, and form plugin tables contain personal data under UK GDPR and the Irish Data Protection Act 2018.

#Minimisation and the Data Protection Commission

The DPC and the UK ICO expect you to pseudonymise order exports used in development. Strip billing emails, replace phone numbers, and document retention in your record of processing activities.

#Consumer Rights Act and checkout plugins

If a maintenance script wipes session transients during peak trading, consumers on UK sites may lose basket state. Coordinate database purges with marketing calendars, especially around Black Friday and regulated financial product comparisons.

#PCI and logging tables

Some payment plugins log gateway responses in custom tables. Before bulk DELETE, confirm with your acquirer whether those logs are evidence for chargeback disputes. UK merchants often keep anonymised payment metadata longer than generic post revisions.


#EXPLAIN and slow query log for WordPress

Use EXPLAIN on suspicious queries before adding indexes blindly:

EXPLAIN SELECT post_id FROM wp_postmeta WHERE meta_key = '_price' LIMIT 10;

If the type column shows ALL, the query scans the full table. Enable the slow query log on staging with a threshold of 100 ms, reproduce checkout and admin list views, then index only the columns that appear in production traces.

#WooCommerce admin tables

Order list screens often join wp_posts and wp_postmeta. Plugins that add custom order fields without indexes are a common cause of admin timeouts on Irish and UK stores above ten thousand orders.


#What should a database checklist include?

Learn more about WordPress speed optimization at WPPoland.

  1. Backup: Always backup before working on the database.
  2. Engine: Ensure all tables are InnoDB.
  3. Autoload: Check autoloaded options size (aim for < 800KB).
  4. Cleaning: Remove revisions, spam, and expired transients.
  5. Indexes: Check if heavy queries use indexes.
  6. Prevention: Configure wp-config.php to limit trash creation.
  7. Automation: Weekly WP-CLI maintenance on staging, then production.
  8. Monitoring: Query Monitor and slow query log after every major plugin upgrade.

#Staging dumps and the UK GDPR

Irish and UK agencies often clone production weekly. Treat every dump as personal data: hash emails, rotate staging credentials, and restrict who can download SQL files from object storage.

#Black Friday and coupon transients

Bulk transient deletes during peak sales erase baskets. Schedule maintenance with merchandising teams, especially on comparison sites regulated under consumer law.

#MariaDB versus MySQL in 2026

Managed hosts on AWS RDS or PlanetScale often run MariaDB 10.11+ with different optimiser defaults than Oracle MySQL. After engine conversion, run OPTIMIZE TABLE on staging, then compare SHOW TABLE STATUS row counts. InnoDB buffer pool sizing still matters more than micro-optimising individual plugins.

When your database is lean and fast, PHP uses less memory, and users get content instantly. This is the foundation of modern WordPress.

Next step

Turn the article into an actual implementation

This block strengthens internal linking and gives readers the most relevant next move instead of leaving them at a dead end.

Frequently asked questions

Practical answers to apply the topic in real execution.

What are the main causes of a slow WordPress database?#
The main causes are excessive post revisions, spam comments, expired transients, autoloaded options left by uninstalled plugins, tables still on the MyISAM engine, and missing indexes on frequently queried columns.
How large should autoloaded options be?#
Autoloaded options should not exceed 800KB-1MB in total. Above that threshold, identify the largest options and switch the autoload flag to 'no', or delete the ones that belong to inactive plugins.
Should I use MyISAM or InnoDB in 2026?#
InnoDB is the mandatory standard in 2026. It offers row-level locking (MyISAM locks the whole table), ACID transactions and foreign keys. Convert every MyISAM table to InnoDB.
How often should I clean the WordPress database?#
Schedule an automatic weekly cleanup for sessions and transients, plus a fuller monthly pass covering revisions, spam, table optimization and a check on autoloaded options.
Which tool is best for monitoring slow queries?#
Query Monitor is the essential plugin. It shows every SQL query, its execution time, which file triggered it, and whether it uses indexes. Install it on development or staging and use it to pinpoint bottlenecks.

Related Articles