How to add a primary key to a MySQL table?

mysql_go picture mysql_go · Feb 27, 2011 · Viewed 238.4k times · Source

This is what I tried but it fails:

alter table goods add column `id` int(10) unsigned primary AUTO_INCREMENT;

Does anyone have a tip?

Answer

The Scrum Meister picture The Scrum Meister · Feb 27, 2011

After adding the column, you can always add the primary key:

ALTER TABLE goods ADD PRIMARY KEY(id)

As to why your script wasn't working, you need to specify PRIMARY KEY, not just the word PRIMARY:

alter table goods add column `id` int(10) unsigned primary KEY AUTO_INCREMENT;