WordPress Database Optimization: Quick Wins and Deep Architecture

9 minutes
WordPress Database Optimization: Quick Wins and Deep Architecture

To optimise a WordPress database, first measure it, then clean what is safe to remove (revisions, spam, expired transients, orphaned metadata, oversized autoloaded options, leftover plugin tables), and cap what grows back. If the site still struggles under heavy data, the problem is usually the data model rather than clutter: high-volume or highly structured records belong in custom tables, not in the shared posts and postmeta tables. Tuning the database server and adding a persistent object cache come last.

In short: back up, measure table sizes and autoloaded data, clean selectively, limit revisions, check that scheduled cleanup really runs, and rebuild tables only after large deletions. Move high-volume structured data to custom tables designed for your queries. Do not expect cleanup alone to fix a site that is slow because of its data model.

What bloats a WordPress database?

  • Post revisions, which accumulate with every save.
  • Trashed posts and spam comments.
  • Orphaned metadata, left behind when posts or plugins are removed.
  • Expired transients, particularly when no persistent object cache is in use.
  • Autoloaded options, data loaded on every request from the options table.
  • Tables left by deactivated plugins, and logs or completed scheduled tasks from active ones.
  • High-volume records stored as posts or metadata, such as events, logs or imports.

How do you measure before cleaning?

Start with a backup and two measurements: which tables are large, and how much data WordPress loads on every request. Run these on a staging copy first. The queries assume the default wp_ prefix, so adjust them if yours differs.

-- Size of each table in MB (largest first)
SELECT table_name,
       ROUND( ( data_length + index_length ) / 1024 / 1024, 2 ) AS size_mb
FROM information_schema.tables
WHERE table_schema = DATABASE()
ORDER BY ( data_length + index_length ) DESC
LIMIT 20;

-- Total autoloaded options in bytes (default wp_ prefix)
SELECT SUM( LENGTH( option_value ) ) AS autoload_bytes
FROM wp_options
WHERE autoload IN ( 'yes', 'on', 'auto-on', 'auto' );

-- The ten largest autoloaded options
SELECT option_name, LENGTH( option_value ) AS bytes
FROM wp_options
WHERE autoload IN ( 'yes', 'on', 'auto-on', 'auto' )
ORDER BY bytes DESC
LIMIT 10;

WP Engine recommends keeping total autoloaded data below 800 KB as a rule of thumb for its platform. Treat that as a guide, not a law, and look at the largest options first, because one plugin is often responsible. Also use a query profiler such as Query Monitor, or the slow query log, to see which queries actually cost time.

What can you safely clean?

ItemHowTake care
Post revisionsDelete old ones, then cap future ones with the WP_POST_REVISIONS constant in wp-config.phpKeep enough for editors to recover work
Trash and spamEmpty the trash and delete spam commentsConfirm nothing in the trash is still needed
Orphaned metadataDelete rows whose parent no longer existsVerify that no plugin relies on them, and back up first
Expired transientsDelete expired transients, or rely on core cleanupSee below: with an external object cache, core cleanup does nothing
Leftover plugin tablesDrop tables of plugins you have removedIdentify the owner by prefix and confirm the plugin is gone
Large autoloaded optionsFix the plugin setting, or turn autoload off for that optionDo not switch autoload off blindly, as some options are needed on every request

On transients: WordPress deletes expired transients through a scheduled task, but that function does nothing when an external object cache is used, because transients then live in the cache rather than the database. Rows left from before the cache was installed may still need a manual cleanup.

Cleanup plugins such as WP-Optimize, Advanced Database Cleaner and WP-Sweep run these steps from the dashboard. WP-CLI does the same from the command line, which is easier to script and review:

# Always take a backup first, and test on a staging copy.
wp db export backup-before-cleanup.sql

# Delete expired transients
wp transient delete --expired

# Delete post revisions
wp post delete $(wp post list --post_type=revision --format=ids)

# Reclaim space on a table after large deletions (quiet period)
wp db query "OPTIMIZE TABLE wp_postmeta;"

Adapt and test these commands on staging before running them on production.

Does OPTIMIZE TABLE help?

Sometimes. MySQL’s documentation says OPTIMIZE TABLE reorganises the physical storage of table data and indexes to reduce space and improve I/O, and recommends it after substantial inserts, updates or deletes. It also notes that InnoDB does not fragment the way legacy engines do, so running it on a schedule by default is not necessary. Use it after large deletions, expect it to rebuild the table, plan for time and disk space, and run it in a quiet period. The mechanics for big tables are covered in ALTER TABLE on a large MySQL table.

When are quick wins not enough?

WordPress stores most content in the shared posts and postmeta tables. That is flexible and works well for most sites, but it strains when a site holds a very large volume of structured records or queries them by many fields. Warning signs:

  • Slow queries that filter on several meta keys.
  • A postmeta table far larger than the posts it describes.
  • Imports, logs or events written as posts.
  • Reports that need joins across many meta rows.
  • Cleanup that helps for a week and then the problem returns.

Ask four questions before a project: will you store thousands of structured records of one kind, do you need to filter or sort them by several fields, do the records have relations to each other, and do they have a fixed retention period? A yes to any of these suggests designing custom tables from the start. Running several sites on multisite does not solve high data volume inside one site’s tables.

How do established products handle this?

WooCommerce is the clearest example. Orders were stored as posts and post meta, and High-Performance Order Storage moves them into dedicated tables, enabled by default for new stores from WooCommerce 8.2. Many plugins that handle high-volume records use their own tables for the same reason. See what database WooCommerce uses and our WooCommerce work.

How do you design a custom table?

  1. Model the domain: entities, attributes and relationships, before writing SQL.
  2. Index for real queries: add indexes for the filters and joins you run, check them with EXPLAIN, and prefer composite indexes where queries combine columns.
  3. Use InnoDB, which is the MySQL default and supports transactions and crash recovery, unless you have a specific reason not to.
  4. Query safely: use $wpdb with prepared statements for every value that comes from outside.
  5. Version the schema: create and update tables with dbDelta, and store a schema version so upgrades run once.

A minimal example, with an events table indexed for the queries it will serve. Names and columns are illustrative:

function wlc_install_events_table() {
    global $wpdb;

    $table   = $wpdb->prefix . 'wlc_events';
    $charset = $wpdb->get_charset_collate();

    $sql = "CREATE TABLE $table (
        id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
        post_id bigint(20) unsigned NOT NULL,
        event_type varchar(50) NOT NULL,
        created_at datetime NOT NULL,
        payload longtext NULL,
        PRIMARY KEY  (id),
        KEY post_created (post_id, created_at),
        KEY type_created (event_type, created_at)
    ) $charset;";

    require_once ABSPATH . 'wp-admin/includes/upgrade.php';
    dbDelta( $sql );
}

dbDelta is strict about formatting, such as two spaces after PRIMARY KEY, so follow its documentation and test an upgrade from an older schema. Standards for this kind of work are in best practices for custom WordPress development.

What about database server tuning?

  • Buffer pool: the InnoDB buffer pool is one of the most important settings. A common guideline is 70 to 80 percent of memory on a dedicated database server, and less when the server also runs the web stack.
  • Separate infrastructure: on heavy sites, run the database on its own server so the web and database workloads do not compete.
  • Persistent object cache: Redis or Memcached reduces repeated queries and keeps transients out of the options table.
  • Measure each change: change one setting at a time, and watch real queries.

How do you maintain custom tables over time?

Core cleanup does not know your tables, so give each one a retention policy. Schedule deletion of old rows, in batches for large tables, and monitor table size. WP-Cron runs when pages are loaded, so tasks can run late on a quiet site, and a real server cron is more predictable for retention jobs. TRUNCATE empties a table instantly, but it removes every row and cannot be rolled back, so use it only for data you can afford to lose.

Speed is the outcome you care about, so measure it, see how page speed affects search rankings and how important Core Web Vitals are for SEO.

If you are not sure whether your database needs a clean-up or a redesign, a technical audit can show which it is. We cover tuning and caching in our performance work, build custom tables through WordPress development, and keep them healthy with growth and care.

FAQ

How often should I clean my database?

There is no fixed schedule. Measure first, then clean when tables or autoloaded data grow. High-volume sites benefit from automated retention rules.

Will optimising the database improve page speed?

It can, especially on a neglected site. If a site is slow because of its data model or heavy queries, cleanup alone will not be enough.

Do small sites need custom tables?

No. The default model handles blogs, brochure sites and modest shops well.

Is it safe to run cleanup plugins on a live site?

Usually, but take a backup first, because deletions are hard to reverse. Test on staging for anything beyond routine cleanup.

Should I use a plugin or WP-CLI?

Either works. WP-CLI is easier to script and review, while plugins are convenient for editors and small sites.

Does a persistent object cache replace database optimisation?

No. It reduces repeated queries and keeps transients out of the database, but bloat, slow queries and a poor data model still need fixing.

Pwel Zmyslowski

Paweł Zmysłowski

CEO WLC.team

At White Label Coders responsible for the sales process and sales team, still involved in the analytical and advisory roles in case of more complex projects.

Author page

Is your WordPress “working, but slow”?

MORE ARTICLES

Read also

  • How can I streamline the content approval process?
    16 minutes

    How can I streamline the content approval process?

    Streamlining your content approval process means setting up WordPress workflows that reduce review layers, automate notifications, and establish clear responsibilities. The most effective approaches combine WordPress user roles, editorial workflow plugins, standardised Gutenberg blocks, and centralised data management to remove bottlenecks. Together with agile methods and better communication protocols, they let content teams publish faster…

    Read

  • Why do my comparison tables cause layout shift?
    11 minutes

    Why do my comparison tables cause layout shift?

    Comparison tables often cause layout shift because parts of them load without reserved space, so content jumps around as the page renders. This happens when images lack dimensions, dynamic data loads without placeholders, or custom fonts reflow text after the first paint. Layout shift hurts user experience and your Core Web Vitals, which feed into…

    Read

  • How do you implement multiple payment gateways in iGaming platforms?
    11 minutes

    How do you implement multiple payment gateways in iGaming platforms?

    Implementing multiple payment gateways in iGaming platforms involves integrating several payment processors to offer diverse payment options, ensure regulatory compliance, and maximise transaction success rates. This approach requires careful technical planning, strong security measures, and intelligent routing systems. The process typically involves API integrations, database management, and thorough testing to create smooth payment experiences for…

    Read