Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 740
jojo Avatar asked Jan 01 '11 17:01

jojo


People also ask

Can I add primary key to existing table?

Because a table can have only one primary key, you cannot add a primary key to a table that already has a primary key defined. To change the primary key of a table, delete the existing key using a DROP clause in an ALTER TABLE statement and add the new primary key.

What happens when a table doesn't have a primary key?

Every table can have (but does not have to have) a primary key. The column or columns defined as the primary key ensure uniqueness in the table; no two rows can have the same key. The primary key of one table may also help to identify records in other tables, and be part of the second table's primary key.

What Cannot be done if the table has no primary key?

Even if you do not add a primary key to an InnoDB table in MySQL, MySQL adds a hidden clustered index to that table. If you do not define a primary key, MySQL locates the first UNIQUE index where all the key columns are NOT NULL and InnoDB uses it as the clustered index.


Video Answer


2 Answers

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;
like image 140
Jason McCreary Avatar answered Oct 15 '22 10:10

Jason McCreary


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
like image 23
DrColossos Avatar answered Oct 15 '22 11:10

DrColossos