OPTIMIZE is a maintenance statement that rewrites the physical storage of a table and updates its indexes. In MySQL and MariaDB it maps to ALTER TABLE ... FORCE, creating a new copy of the table, removing deleted rows, compressing data pages, and rebuilding all secondary indexes. The operation frees disk space from UPDATE and DELETE churn, improves index statistics, and can coalesce adjacent free space. It is blocking for MyISAM tables and online for InnoDB when innodbaoaoise DDL is enabled. When used with partitioned tables, each partition is rebuilt. The statement can be safely replicated by adding the NO_WRITE_TO_BINLOG | LOCAL modifier. Other systems offer similar commands under different names (VACUUM, ANALYZE, REINDEX). Run OPTIMIZE during low-traffic windows or on replicas to avoid lock contention.
NO_WRITE_TO_BINLOG
- LOCAL keyword Prevents the statement from being written to the binary log, so replicas do not run it.table_name
- identifier One or more existing tables or views to optimize, comma-separated.ALTER TABLE, ANALYZE TABLE, REPAIR TABLE, VACUUM, REINDEX
MySQL 3.23
Run it after bulk DELETE or UPDATE operations, or during scheduled maintenance to keep tables compact and statistics fresh.
For InnoDB tables with online DDL enabled it permits concurrent reads and writes; MyISAM tables are fully locked.
Have enough free space for a temporary copy of the largest index or the entire table, whichever is greater.
No. VACUUM reclaims space and updates statistics in PostgreSQL, but the syntax and internal mechanics differ. Use OPTIMIZE only in MySQL-compatible systems.