MySQL ですべてのテーブルを一括で OPTIMIZE する方法
今日も小ネタで、 MySQL で特定のデータベース内のすべてのテーブルを一括で OPTIMIZE する方法についてです。
確認時のバージョン
- MySQL
5.7or8.0
MySQL ですべてのテーブルを OPTIMIZE する方法
早速結論ですが、 mysqlcheck コマンドの --optimize オプションを使えば OK です:
mysqlcheck --optimize --user="$MYSQL_USER" --password="$MYSQL_PASSWORD" "$MYSQL_DATABASE"ちなみに、これはこの方法( mysqlcheck --optimize )にかぎったことではありませんが、 InnoDB テーブルでは OPTIMIZE TABLE の代わりに ALTER TABLE ... FORCE が実行されるようになっています。
出力としては「 Table does not support optimize, doing recreate + analyze instead 」というメッセージが出力されます。
出力サンプル:
mysqlcheck --optimize --user="$MYSQL_USER" --password="$MYSQL_PASSWORD" "$MYSQL_DATABASE"
(略)
mydb.table_a
note : Table does not support optimize, doing recreate + analyze instead
status : OK
(略)MySQL 公式のドキュメントにも説明があるので、詳細に興味のある方はそちらをご覧ください。
参考 1:
For InnoDB tables,
OPTIMIZE TABLEis mapped toALTER TABLE ... FORCE, which rebuilds the table to update index statistics and free unused space in the clustered index. This is displayed in the output ofOPTIMIZE TABLEwhen you run it on an InnoDB table, as shown here:
参考 2:
Running
ALTER TABLE tbl_name ENGINE=INNODBon an existing InnoDB table performs a “null”ALTER TABLEoperation, which can be used to defragment an InnoDB table, as described in Section 15.11.4, “Defragmenting a Table”. RunningALTER TABLE tbl_name FORCEon an InnoDB table performs the same function.