§ 023 · MySQL

How to Monitor and Optimize Fragmented Tables in MySQL

Random insertions or deletions in a secondary index can lead to fragmentation, where the physical order of index pages on disk no longer aligns with the logical order of records. A common sign of fragmentation is that a table occupies more space than expected, though determining the exact amount is challenging. InnoDB stores data and indexes in B-trees, with fill factor ranging from 50% to 100%, contributing to this variability.

Monitoring Fragmentation

Fragmented tables typically consume more disk space than expected. They can also cause query slowness. The following query can help identify fragmentation in tables along with the OPTIMIZE command to be run:

Defragmenting Tables

To defragment tables, use the OPTIMIZE TABLE command or rebuild the table using ALTER TABLE. For example:

Note: These operations can be time-consuming. If concurrent DML operations are modifying the table, the size of the temporary online log may exceed the innodb_online_alter_log_max_size configuration. When this limit is reached, a DB_ONLINE_LOG_TOO_BIG error occurs, interrupting the operation. It’s essential to monitor and adjust this setting as needed to prevent issues during large table alterations.

Alternative Approach: pt-online-schema-change

To avoid potential errors during table alterations, consider using the pt-online-schema-change tool. This tool modifies a copy of the table while allowing the original table to remain accessible for reads and writes. It works by creating a new table, applying the desired changes, and then migrating data from the original table to the new one. Once the process is complete, the original table is swapped with the new version. By default, the original table is dropped. Here’s an example:

Conclusion

Regularly monitoring and optimizing fragmented tables is essential to maintaining MySQL performance and avoiding wasting disk usage.

References

Written by

Vinicius Grippa

Writes this blog. Mostly about databases. Boring on purpose.

More about me →

The floor is yours.

0 comments · Moderated · civil & on-topic

First comment appears here once approved. Questions, corrections, and counterpoints welcome — just no self-promotion.

Add a comment

Your email address is never published. * required

Subscribe · Posted when ready

A quiet, technical email about databases.

One post per send, corrections when I’m wrong, nothing else. No social-media cross-posts. No “what we learned.”

Unsubscribe with any reply