The Ultimate WooCommerce Database Optimization Guide: Eliminate Slow Queries
WooCommerce database optimization in a safe order: autoload, transients, sessions, Action Scheduler, indexes, HPOS caching and MySQL memory. Every command checked against the docs on 15 November 2026, with a backup-first warning.

WooCommerce database optimization comes down to six jobs: move orders into the HPOS tables, keep the autoloaded options small, let expired transients and old sessions go, prune Action Scheduler history, add an object cache, and give MySQL enough memory. Do them in that order, measure after each one, and take a backup before any step that deletes rows. We checked every command and every table name in this guide against the WooCommerce, Action Scheduler, WordPress and WP-CLI sources on 15 November 2026 (WooCommerce 11.3.0, released 11 November 2026).
Most slow stores we are asked to look at are not slow because of one bad query. They carry years of leftovers: a sessions table nobody pruned, an options table full of autoloaded rows from plugins that were removed long ago, and a pile of finished background jobs. This guide covers those leftovers first because they are cheap to fix and easy to verify, then the structural pieces (HPOS, indexes, caching, server memory).
What should I do before touching the database?
Take a full export, then run every change on a staging copy first. Nothing below is hard, but several steps delete rows for good, and a deleted row does not come back from the trash. If your host takes automatic snapshots, confirm you can restore one before you start. A backup you have never restored is a guess.
# Checked against the docs on 15 November 2026. Not run on a live store.
wp db export before-cleanup-$(date +%F).sqlKeep that file off the server you are about to change. If the store is busy, schedule the work for the quietest hours of the week, and run it on staging first so you know how long each step takes. Our WooCommerce staging and migration guide covers how to set up a safe copy.
Warning: every DELETE, tool run and cleanup command below is destructive. Do not paste any of it into a production database without a tested backup and a staging run.
What is WooCommerce database optimization, and where do I start?
It is the work of keeping the tables WooCommerce reads on every request small and indexed, and keeping the tables it only writes to from growing without limit. Start by finding out which tables are big, because the answer changes your plan. A store with a 4 GB Action Scheduler logs table needs a different fix from a store with a slow order list.
# Checked against the docs on 15 November 2026. Not run on a live store.
# Lists every table in the database with its size, largest first
wp db size --tables --order=desc --orderby=sizeThe --order and --orderby options for wp db size were added in WP-CLI 2.7.0, so an older install will reject them. Compare the top ten tables with the table below to see which section of this guide matters most for your store.
Table | What it holds | Safe way to shrink it | Risk |
|---|---|---|---|
| Settings, plus any option marked to load on every request | Switch large options to not autoload; delete expired transients | Low if you change autoload only, medium if you delete rows |
| Cart and customer session data | Let the built-in cleanup run; do not clear it by hand | Clearing it empties live carts |
| Background jobs and their log lines | Shorten the retention period; run the cleaner from WP-CLI | Low for completed and canceled jobs |
| Product, variation and (without HPOS) order meta | Remove rows whose post no longer exists, after a backup | Medium: it is a delete |
| Saved copies of every product and page edit | Cap revisions, then delete old ones | Medium: history is lost |
| Orders, once HPOS is on | Do not trim by hand; use the retention settings | High if edited directly |
Table prefixes differ between sites. We write wp_ throughout; swap in your own prefix, which you can read from $table_prefix in wp-config.php.
How do I speed up the WooCommerce database?
Work through the cheap, low-risk jobs first. This order is the one we follow on client stores, and each row can be measured on its own, so you will know which change helped.
Order | Job | Risk | Where it helps |
|---|---|---|---|
1 | Measure the autoload payload and trim it | Low | Every page load, front and back end |
2 | Delete expired transients | Low | Options table size, admin speed |
3 | Cap Action Scheduler retention | Low | Table size, admin Status pages, backups |
4 | Install a persistent object cache | Medium | Repeated reads of products, terms, options |
5 | Move orders to HPOS | Medium, see our HPOS guide | Order list, order search, checkout writes |
6 | Remove orphaned meta and old revisions | Medium | Table size, some admin queries |
7 | Tune MySQL memory | Medium | Everything, once the data fits in RAM |
Skip step 5 if you are already on HPOS. If you are not, read how to migrate WooCommerce to HPOS safely first; we do not repeat the migration steps here.
Why is my wp_options autoload so big?
Because plugins save data with autoload switched on and nobody ever switches it off. WordPress reads every autoloaded option in one query on every request, so a large payload slows each page before WooCommerce does anything. WordPress Site Health flags the problem at 800,000 bytes by default (set in WordPress core’s Site Health class, and changeable with a filter), which is a sensible number to aim under.
Since WordPress 6.6 the autoload column can hold more than yes and no. The values WordPress loads on startup are yes, on, auto-on and auto, so a query that only checks for 'yes' will undercount on a current site.
-- Checked against the docs on 15 November 2026. Not run on a live store.
-- Read-only. Total size of everything loaded on every request
SELECT SUM(LENGTH(option_value)) AS autoload_bytes
FROM wp_options
WHERE autoload IN ('yes', 'on', 'auto-on', 'auto');
-- The 20 biggest offenders
SELECT option_name, LENGTH(option_value) AS bytes
FROM wp_options
WHERE autoload IN ('yes', 'on', 'auto-on', 'auto')
ORDER BY bytes DESC
LIMIT 20;Read the names. An option called after a plugin you removed two years ago is a candidate. So is anything that looks like a cache, a log or a list of imported rows. Do not guess about options you do not recognise: search the plugin’s code or ask the vendor before you change one.
To stop an option loading on every request without deleting it, use the core function that WordPress added in 6.4. The value stays readable with get_option(); WordPress just fetches it when something asks for it instead of loading it up front.
# Checked against the docs on 15 November 2026. Not run on a live store.
# wp_set_option_autoload() exists since WordPress 6.4; returns true if the value changed
wp eval 'var_dump( wp_set_option_autoload( "some_big_option", false ) );'Two cautions. First, do not use wp option update for this: without a value argument it reads the new value from standard input, so you can overwrite the option by accident. Second, change a few options at a time and re-measure, so you can trace any regression to one change.
How do I clear expired transients safely?
Use the expired-only commands, and leave --all alone on a live store. Expired transients are rows that WordPress would delete the next time something requested them, so removing them early changes nothing a visitor can see. Deleting every transient forces every cached value to be rebuilt at once, and on a busy store that can cause its own slow minute.
# Checked against the docs on 15 November 2026. Not run on a live store.
wp transient delete --expired
# The WooCommerce equivalent (the Status > Tools button, from the command line)
wp wc tool run clear_expired_transients --user=1If your site uses a persistent object cache, transients live in the cache and not in the options table, so you may find very few to delete. That is the good outcome.
How do I stop the sessions table growing?
You mostly do not have to. WooCommerce schedules a cleanup of woocommerce_sessions every 12 hours through Action Scheduler (the woocommerce_cleanup_sessions hook) and deletes expired rows in batches of 100. The table has an index on session_expiry in current versions; a 2025 report had flagged that the cleanup query lacked a usable one on very large tables.
Guest sessions last two days and logged-in sessions last seven by default, and both can be changed with the wc_session_expiration and wc_session_expiring filters. WooCommerce logs a warning when you keep sessions longer than its maximum, because longer sessions mean a bigger table.
The one thing to avoid is the Clear customer sessions tool as a speed trick. WooCommerce’s own description says it deletes all customer session data, including current carts and saved carts in the database. Run it only on a quiet store when you accept that every shopper loses their cart.
If the cleanup is not running, the usual cause is Action Scheduler itself. Check WooCommerce > Status > Scheduled Actions for a large pending or past-due queue, then read our guide to Action Scheduler backlogs and slow checkouts.
How do I shrink the Action Scheduler tables?
Shorten the retention period and run the cleaner. Action Scheduler stores every job in actionscheduler_actions and a log line for each state change in actionscheduler_logs. A built-in cleaner runs daily around 3 am store time and removes complete and canceled actions older than 31 days by default. In current trunk, failed actions are kept for three months by default, through a separate filter for failed actions, so an unusual failure stays visible for a while.
// Checked against the docs on 15 November 2026. Not run on a live store.
// Keep finished and canceled jobs for 7 days instead of 31
// Failed jobs have their own filter: action_scheduler_retention_period_for_failed
add_filter( 'action_scheduler_retention_period', function () {
return 7 * DAY_IN_SECONDS;
} );Put that in a small site plugin, not in the theme, so it survives a theme change. If you already have a large backlog, the daily cleaner works in small batches and can take a long time to catch up. The WP-CLI command lets you push it harder in controlled chunks.
# Checked against the docs on 15 November 2026. Not run on a live store.
# Test the numbers on staging first. --pause waits between batches to spare the database
wp action-scheduler clean --status=complete,canceled --before='7 days ago' --batch-size=500 --batches=20 --pause=1The command defaults to a batch size of 20 and, when you leave out --batches, keeps going until nothing eligible is left. We pass a batch limit on purpose so a mistake stops on its own. Check wp action-scheduler clean --help on your site as well: the options are read from the installed Action Scheduler, and a plugin can bundle an older copy than the one we read.
One more check, read-only. A 2026 GitHub report describes the custom-table store leaving log rows behind after their action was deleted. This query counts them. If it returns a large number, note your Action Scheduler version, check its changelog, and ask your developer before deleting anything.
-- Checked against the docs on 15 November 2026. Not run on a live store.
-- Read-only. Logs whose parent action no longer exists
SELECT COUNT(*)
FROM wp_actionscheduler_logs AS logs
LEFT JOIN wp_actionscheduler_actions AS actions
ON actions.action_id = logs.action_id
WHERE logs.action_id != 0
AND actions.action_id IS NULL;Do post revisions and orphaned postmeta matter?
They matter on stores with a lot of products that get edited often, and they matter much less than the sections above. Every save of a product or page can store a full copy plus its meta, and a store that reprices daily collects them quickly. Cap them first, then decide whether to remove the old ones.
// Checked against the docs on 15 November 2026. Not run on a live store.
// In wp-config.php: keep the last 5 revisions of each post
define( 'WP_POST_REVISIONS', 5 );WordPress keeps unlimited revisions by default (the constant is defined as true), so this line is the only thing standing between you and growth. To delete the revisions you already have, count them, test on staging, then delete in chunks. Revisions use the post status inherit, so name it explicitly.
# Checked against the docs on 15 November 2026. Not run on a live store.
# Count first
wp post list --post_type=revision --post_status=inherit --format=count
# Then delete in chunks of 500 (backup and staging run first)
wp post delete $(wp post list --post_type=revision --post_status=inherit --posts_per_page=500 --format=ids) --forceRun the delete line again until the count reaches the number you want to keep. Deleting posts with --force skips the trash, so it is permanent.
Orphaned postmeta are rows in postmeta whose post is gone. They are harmless individually and add up after a large product import is deleted or a plugin removes posts without cleaning its meta. Count first.
-- Checked against the docs on 15 November 2026. Not run on a live store.
-- Read-only count
SELECT COUNT(*)
FROM wp_postmeta pm
LEFT JOIN wp_posts p ON p.ID = pm.post_id
WHERE p.ID IS NULL;
-- Destructive. Only after a backup and a staging run
DELETE pm
FROM wp_postmeta pm
LEFT JOIN wp_posts p ON p.ID = pm.post_id
WHERE p.ID IS NULL;If the count is in the millions, do not run the delete in one statement on a live database. It locks and logs a lot of rows. Run it on staging to time it, and do it in a quiet window or hand it to your host or developer.
Which database indexes does WooCommerce already have?
More than most guides assume, so look before you add one. We read the table definitions from the WordPress and WooCommerce sources on 15 November 2026.
Table | Indexes that ship |
|---|---|
| Primary key on |
| Primary key, unique |
|
|
|
|
| Primary key, |
Two things follow from this. A status-plus-date query on HPOS orders is already covered by the type_status_date index, so a custom compound index for it adds write cost for no read gain. And earlier versions of this article described a compound index on (meta_key, meta_value) in wp_postmeta. That is wrong: the core schema has only the two single-column indexes above, and we have removed the claim.
If a specific query is slow, prove it before you change the schema. Turn on the slow query log, find the statement, and run EXPLAIN on a staging copy.
-- Checked against the docs on 15 November 2026. Not run on a live store.
-- Read-only. See which indexes a table really has
SHOW INDEX FROM wp_postmeta;
-- Read-only. Replace the query with the slow one you found
EXPLAIN SELECT post_id FROM wp_postmeta WHERE meta_key = '_stock_status' AND meta_value = 'instock';In the output, a type of ALL means a full table scan, and a large rows estimate means MySQL expects to read a lot. Treat an index as a last resort, add it on staging, compare EXPLAIN before and after, and keep it only if it wins. If you cannot tell what the plan means, that is a sign to bring in a database-minded developer. A bad index slows every write to that table.
A word on tooling. Query Monitor shows the queries per request and which plugin issued them, and the wordpress.org directory lists it at 200,000+ active installs (checked 15 November 2026). Use it on staging with a copy of the production data. For production, the MySQL slow query log or your host’s query analytics is the safer source.
What does HPOS data caching do?
It caches order data that the HPOS data store reads, so repeated reads of the same order in a request do not hit the database again. It sits behind its own setting (an option stored as yes or no, read by the orders table controller) and only applies when the custom order tables are in use. Everything else about HPOS, including how to enable it, sync mode and rollback, lives in our HPOS migration guide.
A caching layer is also a place for stale data to hide. One open WooCommerce GitHub issue, reported on 13 November 2026, describes a manually created order keeping a stale auto-draft status after an admin discount on a site running LiteSpeed and Redis, which stops the customer paying. It is one report and we have not reproduced it, so treat it as a reason to test your own admin order flow after you turn caching on, not as proof of a general fault.
Does an object cache speed up WooCommerce?
Yes, for repeated reads, and it also takes pressure off the options table. Without a persistent cache, WordPress keeps its object cache in memory for one request only, then throws it away. With Redis or Memcached behind it, products, terms and options that were read a moment ago are served from memory instead of MySQL.
The most common way to connect Redis is the Redis Object Cache plugin (500,000+ active installs, version 3.0.0, updated 18 September 2026, checked 15 November 2026), or your host’s own cache add-on. Check that your host offers Redis before you buy anything. Site Health will tell you whether a persistent object cache is detected.
Two warnings from experience. A cache can hide a slow query until the cache is flushed, then every slow query arrives together, so fix the queries too. And stock levels are sensitive: if your inventory must be exact, test a flash-sale scenario on staging, with two browsers buying the last unit. Cache bugs in WooCommerce have been reported for term lists and for order data (see the box below), so test after every cache or WooCommerce update.
Does WooCommerce MySQL need tuning?
Sometimes, and mainly one setting: the InnoDB buffer pool, the memory MySQL uses to keep table and index data. If your hot data does not fit in it, MySQL keeps reading from disk, and no query tweak can fix that. The MySQL manual says that on a dedicated database server you might set innodb_buffer_pool_size to 80 percent of physical memory, and warns that competition for memory can cause paging in the operating system.
MySQL 8.4 also has a dedicated-server mode that picks the value for you: 50 percent of detected memory for servers with 1 GB to 4 GB, and 75 percent above 4 GB. Your PHP and web server share the machine on most WooCommerce hosts, so 80 percent is too much there. Start lower and watch memory.
Situation | What the MySQL manual says | Our rule of thumb |
|---|---|---|
Database alone on the server | You might use 80% of physical memory | Start near the 75% the dedicated-server mode uses |
Database shares a machine with PHP and the web server | Memory competition can cause paging | Start well below that and watch swap before raising it |
Managed host or managed database | Not applicable | Ask the host to review it; you may not have access |
On shared or managed hosting you usually cannot change these settings, and the host is the right person to ask. If you can change them, change one value at a time and keep a note of the before and after.
Common mistakes people report
These are recurring problems from the WooCommerce and Action Scheduler GitHub trackers, paraphrased, with the issue linked. Checked 15 November 2026.
- Letting the Action Scheduler logs run unchecked. Reports go back years: a 2021 issue describes a logs table at around 90 million rows, a 2022 issue a huge logs table on a fresh WooCommerce 7.0 install, and a July 2026 issue logs left behind after their actions were removed. Our fix: check the table sizes every month, and set a retention period.
- Assuming the cleanup command catches everything. A July 2026 pull request reports that
wp action-scheduler cleanfiltered by last-modified time, so jobs that were retried recently escaped cleanup even when scheduled long ago. Our fix: re-count after a clean, and do not assume a zero. - Expecting the sessions cleanup to be fast on a huge table. A July 2025 issue reported a long-running delete because the table had no usable index for expiry. Our fix: be on a current WooCommerce version, and keep session lifetimes at their defaults.
- Switching on caching and not re-testing admin order flows. An open issue from 13 November 2026 links HPOS data caching, Redis and LiteSpeed to a stale order status. Our fix: test manual orders, discounts and refunds on staging after any cache change.
- Leaving options out of autoload, or loading too much. A 2024 issue counted 58 separate option queries on a plain WooCommerce install because options that did not exist in the table were looked up one by one. The lesson cuts both ways: autoload is a trade, so measure it before and after. Our fix: trim what is big and never read, and do not turn autoload off for small, hot options.
How do I know the changes worked?
Capture a baseline first, change one thing, and compare. Without numbers you only have a feeling, and cleanup always feels like it helped. Record these before you start:
- Database size and the five largest tables, from
wp db size --tables. - The autoload total from the query above.
- Time to first byte on the shop, a product page, the cart and checkout, measured from the same place each time.
- Query count and slowest queries for those pages from Query Monitor on staging.
- The pending and past-due counts under WooCommerce > Status > Scheduled Actions.
After each change, record the same numbers. Many changes will move the table sizes and nothing else, which is fine: a smaller database also backs up and restores faster. Expect a bigger change in page speed from the object cache and the autoload cleanup than from deleting revisions. For the wider picture of speed work beyond the database, our WooCommerce performance checklist and the guide to scaling past 100,000 products go through server, caching and front-end changes.
Frequently asked questions
How often should I run these cleanups?
Set the automatic parts once (retention period, revision limit, object cache), then review table sizes and the autoload total once a month. We have no magic number; the right gap is whatever stops the tables growing between reviews.
Is it safe to delete post revisions?
It is safe for the site and permanent for the history. Revisions are copies used for the editor’s undo history, so deleting them does not change the live product or page. Back up first, and keep the most recent few.
Can I do this on managed WordPress hosting?
Most WP-CLI and SQL steps work if your host gives you SSH or a database tool. Server settings such as the buffer pool usually need a support ticket. Ask the host before you run anything destructive, because some hosts already run their own cleanups.
Do I need Redis to see any benefit?
No. The autoload trim, the retention period and the transient cleanup help without it. Redis is worth adding when the same data is read many times per request or the options table is a hot spot.
When should we call someone in?
Call someone in when the database is large enough that a mistake costs real money, when a query is slow and you cannot tell why, or when you have no tested restore. Our team at WooCustomDev audits WooCommerce databases, reads the slow query log with you and makes the changes on staging first. You can contact us or look at our WooCommerce development services. Many stores will not need us, and a careful afternoon with this guide is enough.
Sources we checked on 15 November 2026: the WordPress.org plugin API for WooCommerce (11.3.0, updated 11 November 2026), the WooCommerce and Action Scheduler repositories on GitHub (session handler, queue cleaner, WP-CLI clean command, orders table schema, system status tools), WordPress core (schema.php, option.php, class-wp-site-health.php), the WP-CLI command handbook (db size, db export, transient delete, post list, post delete, option list) and the MySQL 8.4 reference manual.
Plugins we build and run
We maintain these ourselves, which is why we can support them on your site.
- BuddyNextThe self-hosted community engine for WordPress
- BuddyXFree community theme, Pro when you outgrow it
- ReignPremium community theme. Add pieces, build anything
- JetonomyCommunity forum and Q&A for WordPress
- EventonomyEvents and RSVPs for WordPress communities
- LearnomyCourses and learning communities on WordPress
- ListoraDirectories and listings your members can browse
- SnipShareCode sharing built for developer communities
- WB Ad ManagerAd placements that turn traffic into revenue
- WP Career BoardA job board your community actually uses
- WP Sell ServicesSell services with offers, orders, and payouts
- MediaVersePhotos, video, and media albums for members
- WB GamificationPoints, badges, and rewards that keep members active
- Product RoadmapPublic roadmaps with voting your users trust
- KanbanomyProject management with a client portal, on your own WordPress site



