OPTIMIZE TABLE on InnoDB table resets AUTO_INCREMENT counter
MySQL recently fixed a known bug (I was not aware of this before) of OPTIMIZE TABLE (in MySQL Server 5.1.55, 5.5.9) in which OPTIMIZE TABLE statement was not preserving the AUTO_INCREMENT counter on OPTIMIZE TABLE operation.
Want to see yourself? Lets do it (code taken from the MySQL bug report)
CREATE TABLE a (a INTEGER PRIMARY KEY NOT NULL AUTO_INCREMENT) ENGINE=INNODB; INSERT INTO a VALUES (); INSERT INTO a VALUES (); INSERT INTO a VALUES (); DELETE FROM a ; SHOW TABLE STATUS LIKE 'a';
In the below table status, you can see the AUTO_INCREMENT value is 4 (even after deleting all the rows which is normal behavior).
mysql> SHOW TABLE STATUS LIKE 'a'\G
*************************** 1. row ***************************
Name: a
Engine: InnoDB
Version: 10
Row_format: Compact
Rows: 3
Avg_row_length: 5461
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 4194304
Auto_increment: 4
Create_time: 2011-02-20 07:52:18
Update_time: NULL
Check_time: NULL
Collation: latin1_swedish_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)
Now execute the OPTIMIZE TABLE command and check the table status
OPTIMIZE TABLE a; SHOW TABLE STATUS LIKE 'a';
mysql> SHOW TABLE STATUS LIKE 'a'\G
*************************** 1. row ***************************
Name: a
Engine: InnoDB
Version: 10
Row_format: Compact
Rows: 0
Avg_row_length: 0
Data_length: 16384
Max_data_length: 0
Index_length: 0
Data_free: 4194304
Auto_increment: 1
Create_time: 2011-02-20 07:52:18
Update_time: NULL
Check_time: NULL
Collation: latin1_swedish_ci
Checksum: NULL
Create_options:
Comment:
1 row in set (0.00 sec)
MySQL fixed this bug 5 years after the bug report.
So be careful with OPTIMIZE TABLE if you have older MySQL versions.
TRUNCATE TABLE reset the AUTO_INCREMENT to 1 so don't confuse this example with TRUNCATE TABLE.