I’ve a table with ID column, auto increment. Because of the bad migration a while a go, and I only noticed this now, form entries were all stored as ID 0. So now I have two problems: around 1000 entries with 0 as ID as well as column definition and AUTO INCREMENT value.
Latter is an easy fix, and I’m not concerned about that. But, is there a SQL command that I can use to programmatically fix IDs so that they’re set just as if the AUTO INCREMENT was working properly the whole time.
The last proper
id is 2540. After that entry, all the entries have id 0. There’s 3200 rows in the table. So, all in all, I want to fix the table ID column so that all the IDs 0 are changed from 2541 to 3200. NOTE: I can’t afford to change the old working IDs.
2
Answers
In case if you can reset ALL id values you can simply drop the id column and re-create it with right configuration:
test solution here
Another way – create procedure that fix table rows one by one:
test here
Don’t forget to set column auto_incremet and primary key after update:
Here’s a demo:
The use of user-defined variables in this way is discouraged and gives a warning, but at least in MySQL 8.0 it still works (I tested the above on MySQL 8.1.0).
You can then verify that the rows have been updated the way you want.
You should change
id
to be a primary key, then it won’t allow duplicates.You should also make sure your
sql_mode
option does NOT includeNO_AUTO_VALUE_ON_ZERO
. If you insert a 0 value to an auto-increment column, it should generate a new incremented value.