Hands-on Lab·MySQL
MySQL Fragmentation and OPTIMIZE TABLE
A third of the rows deleted and the table is exactly as large as before - 20.5 MB either way. Deleting rows does not return space, and OPTIMIZE TABLE rebuilding the table is what finally does.
Monitoring and Operations Guide 43 of 45 Intermediate
- OSUbuntu 26.04 LTS
- MySQL8.4.10-0ubuntu0.26.04.1
- Topologydb-a01 source, db-b01 and db-c01 replicas
- TimeAbout 15 min
OPTIMIZE TABLE on InnoDB is not an optimisation in the MyISAM sense - it rebuilds the table. Since 5.6 it is online for most cases, but it still copies the data and needs room to do it.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| db-a01 | 192.168.0.81 | Ubuntu 26.04 LTS | Primary / Source / Replica Set Member 1 | 2 Core | 4 GB | 50 GB |
This guide includes
Use this when deleting a third of a table frees no space at all. This matters because InnoDB keeps the pages - the file stays exactly as large as it was, and only a rebuild returns the space.
- deleting every third row, scattered through the table
- finding the table is exactly as large as it was before
- rebuilding it with
OPTIMIZE TABLE, and reading the note it prints first
Before you start
- The
eventstable with 400,000 rows. - Free disk space of at least the table's size - the rebuild needs a copy.
-
Delete a third of the rows
-
Rebuild the table