OPTIMIZE [NO_WRITE_TO_BINLOG | LOCAL] TABLEtbl_name
[,tbl_name
] ...
OPTIMIZE TABLE
should be used if
you have deleted a large part of a table or if you have made
many changes to a table with variable-length rows (tables that
have VARCHAR
,
VARBINARY
,
BLOB
, or
TEXT
columns). Deleted rows are
maintained in a linked list and subsequent
INSERT
operations reuse old row
positions. You can use OPTIMIZE
TABLE
to reclaim the unused space and to defragment
the data file. After extensive changes to a table, this
statement may also improve performance of statements that use
the table, sometimes significantly.
This statement requires SELECT
and INSERT
privileges for the
table.
OPTIMIZE TABLE
is supported for
partitioned tables, and you can use ALTER TABLE ...
OPTIMIZE PARTITION
to optimize one or more partitions;
for more information, see Section 12.1.6, “ALTER TABLE
Syntax”, and
Section 18.3.3, “Maintenance of Partitions”.
OPTIMIZE TABLE
works
only for MyISAM
,
InnoDB
, and ARCHIVE
tables. It does not work for tables created
using any other storage engine.
For MyISAM
tables,
OPTIMIZE TABLE
works as follows:
If the table has deleted or split rows, repair the table.
If the index pages are not sorted, sort them.
If the table's statistics are not up to date (and the repair could not be accomplished by sorting the index), update them.
For InnoDB
tables,
OPTIMIZE TABLE
is mapped to
ALTER TABLE
, which rebuilds the
table to update index statistics and free unused space in the
clustered index. This is displayed in the output of
OPTIMIZE TABLE
when you run it on
an InnoDB
table, as shown here:
mysql> OPTIMIZE TABLE foo; +----------+----------+----------+-------------------------------------------------------------------+ | Table | Op | Msg_type | Msg_text | +----------+----------+----------+-------------------------------------------------------------------+ | test.foo | optimize | note | Table does not support optimize, doing recreate + analyze instead | | test.foo | optimize | status | OK | +----------+----------+----------+-------------------------------------------------------------------+
You can make OPTIMIZE TABLE
work
on other storage engines by starting mysqld
with the --skip-new
or
--safe-mode
option. In this case,
OPTIMIZE TABLE
is just mapped to
ALTER TABLE
.
OPTIMIZE TABLE
returns a result
set with the following columns.
Column | Value |
---|---|
Table | The table name |
Op | Always optimize |
Msg_type | status , error ,
info , note , or
warning |
Msg_text | An informational message |
Note that MySQL locks the table during the time
OPTIMIZE TABLE
is running.
By default, OPTIMIZE TABLE
statements are written to the binary log so that they will be
replicated to replication slaves. Logging can be suppressed with
the optional NO_WRITE_TO_BINLOG
keyword or
its alias LOCAL
.
OPTIMIZE TABLE
does not sort
R-tree indexes, such as spatial indexes on
POINT
columns. (Bug#23578)