29

I have encountered a problem in that I already have a composite primary key in a MYSQL table. But now I have added another column to that table and due to some requirement changes, I have to modify that composite primary key in such a way that I need to add that previously mentioned column to that composite primary key list. Can anyone tell me how to alter that table without dropping existing composite primary key. I am doing this in a Rails project

nash
  • 705
  • 4
  • 14
  • 21

2 Answers2

42

You can't alter the primary key. You have to drop and re-add it:

ALTER TABLE MyTable
  DROP PRIMARY KEY,
  ADD PRIMARY KEY (old_col1, old_col2, new_col);
Jeremy Stein
  • 19,171
  • 16
  • 68
  • 83
1

but if a key no exist? example:

ALTER TABLE xxxx ADD id INT NOT NULL AUTO_INCREMENT, ADD PRIMARY KEY(id,id2,id3);
bensiu
  • 24,660
  • 56
  • 77
  • 117