MySQL - Make an existing Field Unique

Lothar picture Lothar · Feb 18, 2011 · Viewed 181.9k times · Source

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?

Answer

WuHoUnited picture WuHoUnited · Feb 18, 2011
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