When Magento deletes many rows, for example old carts, cron history or logs, MySQL keeps the freed space inside the table for later reuse. The table file stays just as big on disk, and queries still read through the gaps.

Find fragmented tables

SELECT TABLE_NAME,
       ROUND(DATA_LENGTH/1048576) AS data_mb,
       ROUND(DATA_FREE/1048576) AS free_mb
  FROM information_schema.TABLES
 WHERE TABLE_SCHEMA = DATABASE() AND DATA_FREE > 100*1048576
 ORDER BY DATA_FREE DESC LIMIT 15;

Tables with a large free_mb compared with data_mb are worth rebuilding. Typical candidates are quote, cron_schedule, search_query, report tables and customer visitor logs.

How to rebuild a table

OPTIMIZE TABLE quote;

InnoDB rebuilds the table and returns the free space to the filesystem.

Do it safely

  • Run it at the quietest time of day. On large tables, the rebuild can block or slow queries on that table for minutes.
  • Make sure the disk has free space at least the size of the table, because MySQL writes a full new copy first.
  • For very large, busy tables, use pt-online-schema-change from Percona Toolkit, which rebuilds without blocking:
    pt-online-schema-change --alter "ENGINE=InnoDB" D=magento,t=quote --execute
  • Take a backup first.

Stop it coming back

Fragmentation comes from cleanup. That is good, but it means rebuilding the busiest cleanup tables every few months is normal maintenance. It is not a sign that something is wrong.

Catch it automatically

MageMonitor checks for this every few minutes as part of its Database checks, and alerts you by email, Slack or webhook the moment it appears, with the exact commands to fix it. See MageMonitor for Magento 2.

Related fixes