Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How add unique key to existing table (with non uniques rows)

I want to add complex unique key to existing table. Key contains from 4 fields (user_id, game_id, date, time). But table have non unique rows. I understand that I can remove all duplicate dates and after that add complex key.

Maybe exist another solution without searching all duplicate data. (like add unique ignore etc).

UPD I searched, how can remove duplicate mysql rows - i think it's good solution. Remove duplicates using only a MySQL query?

like image 333
yAnTar Avatar asked Mar 06 '13 18:03

yAnTar


People also ask

How do I add a unique key to an existing table?

Sometimes we want to add a unique key to the column of an existing table; then, this statement is used to add the unique key for that column. Following are the syntax of the ALTER TABLE statement to add a unique key: ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE(column_list);

How do I add a unique key to an existing column in SQL?

Set column as unique in SQL Server from the GUI:Open SQL Server Management Studio. Right click your Table, click "Design". Right click the column you want to edit, a popup menu appears, click Indexes/Keys. Click the "Add" Button.

How do I make a column unique in an existing table?

Syntax to add UNIQUE to an existing field. alter table yourTableName add UNIQUE(yourColumnName); Applying the above syntax in order to add UNIQUE to column 'name'. Now we cannot insert duplicate records into the table, since we have set the field to be unique.

Can a table have 2 unique keys?

Yes a table can have n number of unique and foreign keys. Unique key constraints are used to ensure that data is not duplicated in two rows in the database. One row in the database is allowed to have null for the value of the unique key constraint.


1 Answers

You can do as yAnTar advised

ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY 

OR

You can add a constraint

ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time) 

But I think to not lose your existing data, you can add an indentity column and then make a composite key.

like image 176
Igor Lozovsky Avatar answered Sep 24 '22 15:09

Igor Lozovsky