Monday, January 24, 2011

Reset auto_increment value of a MySQL database table after deleting several rows

In a MySQL table with a lot of data, it is very common that last few rows will get deleted frequently. If any column has auto_increment, this will result in a gap in the generated column values. It is very easy to reset the auto_increment value to the correct value which will not result in any gap between the column values. Of course, it is only possible to prevent the gap if the deleted rows were the last few rows of the table. Here is the sql that will reset auto_increment:
ALTER TABLE table_name_to_reset AUTO_INCREMENT=1
That's it. Hope this helps.