jojo
jojo

Reputation: 13843

Add a primary key column in to a no primay key old table

If a table, data might be duplicated amount rows, and there is not primary key for every row,

can i add an column to be a primary key?

Upvotes: 17

Views: 34890

Answers (2)

Jason McCreary
Jason McCreary

Reputation: 72991

Yes. Add a new column and set it as the primary key with AUTO_INCREMENT. Doing so will create a new column and automatically add a unique id for each row.

ALTER TABLE old_table ADD pk_column INT AUTO_INCREMENT PRIMARY KEY;

Upvotes: 25

DrColossos
DrColossos

Reputation: 12998

This is possible with ALTER TABLE (Assuming you have a column that you want to use as a PK)

ALTER TABLE table 
ADD PRIMARY KEY(column)

Alternativly:

ALTER TABLE table 
ADD your_pk_column INT(11) AUTO_INCREMENT PRIMARY KEY

Upvotes: 19

Related Questions