Wednesday, June 1, 2011

Useful SQL snippets: Resetting AUTO_INCREMENT

Scenario: You've created a table in SQL with an auto-incrementing identifier. You've got records 1-99 all entered and, for the most part, there are no "holes" where you've deleted any records. But then somehow, you add one more entry to the table and instead of assigning its ID to 100, the ID gets set to 150 (or some other value than you were expecting). How do you reset that?

Solution:
   ALTER TABLE your_table AUTO_INCREMENT=100;

Q: Is it guaranteed that SQL will increment at the number I specify, no matter what?

A: No. SQL is smart enough to first count your records, find the highest-used ID value, and then use the next one. If you have 100 records already, it will start at 101, even if you specify:
   ALTER TABLE your_table AUTO_INCREMENT=13;

This will NOT "fill in the gaps" if you have removed records in the middle of the recordset:

+----+-------------------------+---------------------+---------------------+
| Id | Name                    | Creation            | Modified            |
+----+-------------------------+---------------------+---------------------+
| 10 | Shakespeare, William    | 2011-05-30 23:05:43 | 2011-05-30 23:05:43 |
| 11 | Steinbeck, John         | 2011-05-30 23:05:43 | 2011-05-30 23:05:43 |
| 12 | Talmage, James E        | 2011-05-30 23:05:43 | 2011-05-30 23:05:43 |
| 15 | Tolkien, J R R          | 2011-05-30 23:05:43 | 2011-05-30 23:05:43 |
| 16 | Tolstoy, Leo            | 2011-05-30 23:05:43 | 2011-05-30 23:05:43 |
| 17 | Twain, Mark             | 2011-05-30 23:05:43 | 2011-05-30 23:05:43 |
+----+-------------------------+---------------------+---------------------+

Here, setting the AUTO_INCREMENT to 13 will NOT fill in records #13 or #14: it will start at 18 (after the last record).

No comments:

Post a Comment