dataiotech Labs
dbaguidedbaguideDBAdataxtoolsdataopsphere
Scripts Library/mysql/#37
Script #37
mysql
Maintenanceread-onlyMin Version: 5.7

MySQL InnoDB Table Fragmentation and Reclaimable Space

Lists tables with large free space (data_free). Identifies candidates for space reclamation with OPTIMIZE TABLE.

#fragmentation#data_free#optimize
mysql · sql
SELECT table_schema, table_name,
       ROUND(data_length / 1048576, 1) AS data_mb,
       ROUND(data_free   / 1048576, 1) AS free_mb,
       ROUND(100 * data_free / NULLIF(data_length + index_length + data_free, 0), 1) AS free_pct
FROM information_schema.tables
WHERE engine = 'InnoDB' AND data_free > 100 * 1048576
ORDER BY data_free DESC
LIMIT 25;
Operational Notes & Remediation Guidance

Run `OPTIMIZE TABLE` or `ALTER TABLE ... ENGINE=InnoDB` during off-peak maintenance hours to rebuild fragmented tablespaces.

Production Safety & Execution Standards
  • This script is designed for read-only diagnostics; it does not alter schema or modify data directly.
  • Prior to executing on production systems under high load, verify the target database version (Min. Version: 5.7).
  • Exercise caution with mutating actions (e.g., terminating sessions or dropping indexes) referenced in the notes section.