SyntaxStudy
Sign Up
MySQL ANALYZE and OPTIMIZE TABLE
MySQL Intermediate 4 min read

ANALYZE and OPTIMIZE TABLE

ANALYZE and OPTIMIZE TABLE

ANALYZE TABLE updates index statistics so the optimizer makes better choices. OPTIMIZE TABLE defragments the table and reclaims space.

Example
-- Update optimizer statistics
ANALYZE TABLE orders;

-- Defragment and reclaim space (rebuilds table)
OPTIMIZE TABLE orders;

-- Check fragmentation
SELECT TABLE_NAME,
       ROUND(DATA_FREE/1024/1024, 2) AS free_mb
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = DATABASE()
ORDER BY DATA_FREE DESC;
Pro Tip

OPTIMIZE TABLE locks the table on non-partitioned InnoDB — schedule during low traffic.