Tuesday, October 13, 2009

Reseting the auto increment value n an mySql database field

I came across this problem that I wanted to reset my auto increment number for the id field which was my primary key. I deleted a few records and so it was now difficult to get the number to start from 1 again and get a nice sequence. One obvious thing to do was manually edit it as my content was not huge. But still I found a correct and automated way to do that:

I made it possible by using PHP's while loop. [NOTE: I will just give the main structure.]

Select ID from
order by ID

then use a while/for loop to iterate through the results, and update each row with a new number for the ID.. you could use a PHP variable to track the current ID number, and increment it with each loop...

Update
set ID=???