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.
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.
EDIT:
Since it’s an int column, you can order them numerically. Just do a
SELECT Ids FROM Table Order By Idsto 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
INTvariable that increments throughout the loop. When you find a gap (no match) – break the loop and use thatINTvalue as yourINSERTid.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.
EDIT #2:
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.
EDIT #3:
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…