Tech-Tidbit: Altering Primary Keys in MySQL
I’ve come to design every database table with an auto-increment id field that is a primary key. However, sometimes I work on projects where tables have no such column and may have duplicate rows. In order to drop the existing primary key definitions I run:
[mysql]
ALTER TABLE mytable DROP PRIMARY KEY;
[/mysql]
Then, I add a new one:
[mysql]
ALTER TABLE `mytable` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST ;
[/mysql]