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?
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.
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.
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.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With