Reputation: 23
I made a table in a mysql database for testing purposes. The id is auto incremented. After doing this(not together)
delete from test where id=4;
alter table test auto_increment = 4;
insert into test(nume) values('dan');
It does not give any errors. But the last id is 5, not 4. Should not this be working?
Upvotes: 0
Views: 10281
Reputation: 1712
This whole procedure has only use in case you do delete the record with the highest id. Should you delete where id=2, you cannot change the autoincrement id. For whatever reason you do not like to get a gap in the id line at id=4, in case of deleting id =2 there will be a gap. So why mess with the ids when after adding a new record id =5 you would have the same kind of gap.
But what about racing conditions. You delete record id=4. two millisec later I add a record, getting id=5. What will happen to the auto increment id?
What legit reason is there for avoiding these gaps?
Upvotes: 0
Reputation: 886
After delete write this query
ALTER TABLE tablename AUTO_INCREMENT = 1
Upvotes: 2
Reputation: 8635
Question yourself, whether you need to alter the primary key. In most legitimate cases - no.
This will partially work, once you insert a row, the ID will be 4, but auto_increment will change to 5.
As a result, next row insertion will give you a primary key duplication error.
Upvotes: 0