Possible Duplicate:
Using unused primary keys
I created a table with an id column with auto increment Now when I deleted the rows with the id's 8,12,30 in that table.
Now when I insert a new record I want to insert the next record into 8 then 12 etc..
Is there a way to get MySQL auto increment to do this for me?
I tried to set autoincrement to some number, but I don't want to do it that way.
Reset the auto increment fieldALTER TABLE `table` AUTO_INCREMENT = number; Replacing 'number' with the result of the previous command plus one and replacing table with the table name. If you deleted all the rows in the table, then you could run the alter table command and reset it to 0.
Using TRUNCATE TABLE Statement. The TRUNCATE TABLE statement in MySQL completely deletes the table's data without removing a table's structure and always resets the auto-increment column value to zero.
In MySQL, the syntax to reset the AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = value; table_name. The name of the table whose AUTO_INCREMENT column you wish to reset.
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
You don't want to use an auto-incrementing column then. If you want to fill in the gaps, set it to an int column and handle the logic in stored proc or insert.
Since it's an int column, you can order them numerically. Just do a SELECT Ids FROM Table Order By Ids
to get all of the Ids and check for the gaps in the returned dataset.
There's probably a smoother way of doing this, but you could loop the results with a cursor and compare to an INT
variable that increments throughout the loop. When you find a gap (no match) - break the loop and use that INT
value as your INSERT
id.
I won't write your code for you, but those are some steps to get you going in the right direction. It should be a really basic bit of programming you should be able to handle.
Hope this helps.
As others have noted, your best move is to just leave the gaps. Unless there's some cap on the table as far as length and Ids MUST be 1-30 (weird), leave it alone. There's no benefit to filling in the gaps.
One more thing to consider: if you really do have to keep 1-30 for some reason, don't delete your rows. Add a column to flag each row as active or not and then just update the rows that are inactive when you need to and then flag them as active. This is VERY hacky, but your requirement is kinda hacky, so...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With