MySQL - Make an existing Field Unique

MysqlUnique Constraint

Mysql Problem Overview


I have an already existing table with a field that should be unique but is not. I only know this because an entry was made into the table that had the same value as another, already existing, entry and this caused problems.

How do I make this field only accept unique values?

Mysql Solutions


Solution 1 - Mysql

ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);

For MySQL 5.7.4 or later:

ALTER TABLE mytbl ADD UNIQUE (columnName);

> As of MySQL 5.7.4, the IGNORE clause for ALTER TABLE is removed and > its use produces an error.

So, make sure to remove duplicate entries first as IGNORE keyword is no longer supported.

Reference

Solution 2 - Mysql

Just write this query in your db phpmyadmin.

ALTER TABLE TableName ADD UNIQUE (FieldName)

Eg: ALTER TABLE user ADD UNIQUE (email)

Solution 3 - Mysql

If you also want to name the constraint, use this:

ALTER TABLE myTable
  ADD CONSTRAINT constraintName 
    UNIQUE (columnName);

Solution 4 - Mysql

CREATE UNIQUE INDEX foo ON table_name (field_name)

You have to remove duplicate values on that column before executes that sql. Any existing duplicate value on that column will lead you to mysql error 1062

Solution 5 - Mysql

The easiest and fastest way would be with phpmyadmin structure table.

USE PHPMYADMIN ADMIN PANEL!

There it's in Russian language but in English Version should be the same. Just click Unique button. Also from there you can make your columns PRIMARY or DELETE.

Solution 6 - Mysql

ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);

is the right answer

the insert part

INSERT IGNORE INTO mytable ....

Solution 7 - Mysql

This code is to solve our problem to set unique key for existing table

alter ignore table ioni_groups add unique (group_name);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLotharView Question on Stackoverflow
Solution 1 - MysqlWuHoUnitedView Answer on Stackoverflow
Solution 2 - MysqlMuhammad Rizwan Kaim KhaniView Answer on Stackoverflow
Solution 3 - MysqlypercubeᵀᴹView Answer on Stackoverflow
Solution 4 - MysqlZulanView Answer on Stackoverflow
Solution 5 - MysqlMKAView Answer on Stackoverflow
Solution 6 - Mysqluser3772326View Answer on Stackoverflow
Solution 7 - MysqlKARTHIKEYAN.AView Answer on Stackoverflow