Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

renumber primary key

How would I reset the primary key counter on a sql table and update each row with a new primary key?

like image 430
Aaron Fischer Avatar asked Oct 23 '08 14:10

Aaron Fischer


2 Answers

I would add another column to the table first, populate that with the new PK.

Then I'd use update statements to update the new fk fields in all related tables.

Then you can drop the old PK and old fk fields.

EDIT: Yes, as Ian says you will have to drop and then recreate all foreign key constraints.

like image 179
Galwegian Avatar answered Oct 05 '22 04:10

Galwegian


Not sure which DBMS you're using but if it happens to be SQL Server:

SET IDENTITY_INSERT [MyTable] ON

allows you to update/insert the primary key column. Then when you are done updating the keys (you could use a CURSOR for this if the logic is complicated)

SET IDENTITY_INSERT [MyTable] OFF

Hope that helps!

like image 31
Zachary Yates Avatar answered Oct 05 '22 04:10

Zachary Yates