[mysql] MySQL - Make an existing Field Unique

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?

This question is related to mysql unique-constraint

The answer is


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.


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

alter ignore table ioni_groups add unique (group_name);

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


ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);

is the right answer

the insert part

INSERT IGNORE INTO mytable ....

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

ALTER TABLE myTable
  ADD CONSTRAINT constraintName 
    UNIQUE (columnName);

Just write this query in your db phpmyadmin.

ALTER TABLE TableName ADD UNIQUE (FieldName)

Eg: ALTER TABLE user ADD UNIQUE (email)