i just wondered, if there is an elegant way of automatically resetting the autoincrement of a mysql table to the lowest value according to the present content.
example:
mytable:
1 content of row 1
2 content of row 2
3 content of row 3
4 content of row 4
5 content of row 5
now the autoincrement will be at 6
but before i insert new contents, i delete row 3,4 and 5. the content would look like this:
1 content of row 1
2 content of row 2
the autoincrement would still be at 6.
and this is the issue.
i would like the autoincrement to be at 3, because it is the lowest possible value according to the inserted IDs.
the would prevent extremely large numbers, if the autoincrement would grow "infinitely" and get out of range of a 12 digits long integer.
thanks for any suggestion!
This depends on your storage engine,
For MyISAM and for InnoDB on MySQL 5.6+, you can set the
AUTO_INCREMENT
value for the table to say1
. That value will automatically be increased to the maximum current value + 1. Do that like this.For InnoDB on MySQL < 5.6, this will not work and you will need to do this manually like this:
Note in that last case, the two queries will need to be run with the same database connection.
Reset Auto Increment IDs.
http://community.spiceworks.com/scripts/show/3042-reset-auto-increment-ids
update all auto increment columns in a database to the smallest possible value based on current values in the databases. We needed to do this after cleaning out a database.
Use a Prepared Statement within a Stored Procedure: