LoginSignup
4
3

More than 3 years have passed since last update.

MySQL 5.7以前のAUTO_INCREMENTはサーバ再起動すると値が変わるがMySQL 8.0では変わらなくなった

Last updated at Posted at 2019-10-10

結論

タイトルの通り、
MySQL 5.7以前のAUTO_INCREMENTはサーバ再起動すると値が変わるが
MySQL 8.0では変わらなくなった

みたいです!

公式リファレンスの引用

引用元: https://dev.mysql.com/doc/refman/8.0/en/innodb-auto-increment-handling.html

If you specify an AUTO_INCREMENT column for an InnoDB table, the in-memory table object contains a >special counter called the auto-increment counter that is used when assigning new values for the column.

In MySQL 5.7 and earlier, the auto-increment counter is stored only in main memory, not on disk. To >initialize an auto-increment counter after a server restart, InnoDB would execute the equivalent of the >following statement on the first insert into a table containing an AUTO_INCREMENT column.
SELECT MAX(ai_col) FROM table_name FOR UPDATE;
In MySQL 8.0, this behavior is changed. The current maximum auto-increment counter value is written to >the redo log each time it changes and is saved to an engine-private system table on each checkpoint. >These changes make the current maximum auto-increment counter value persistent across server restarts.

まとめますと下記の通りかと思います。

MySQL 5.7以前

  • AUTO_INCREMENTはディスクではなくメインメモリにのみ保存される。
  • サーバ再起動後にAUTO_INCREMENTの値を初期化する。
  • AUTO_INCREMENTの値が最大値+1となる。

MySQL 8.0

  • AUTO_INCREMENTの値は、変更されるたびにREDOログに書き込まれ、
    各チェックポイントでシステムテーブルに保存される。
  • サーバ再起動後も現在のAUTO_INCREMENT値が維持される。

この件について調べたきっかけ

あるテーブルのAUTO_INCREMENTが突然1になる事象が発生しました。
リファレンスを参照した結果、サーバ再起動が起因であることがわかりました。

AUTO_INCREMENTが"1"になっていた原因は、
テーブル内のレコードが0件となったタイミングで再起動が行われたためでした。

対象のテーブルは一時保存するような使い方をしており、レコード内のデータの状態が変わったら、物理削除しつつ別のテーブルへ移動させるという実装となっていました。

設計が微妙でしたが、AUTO_INCREMENTの値が変動するというのは予想外でしたorz

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3