English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to make an existing field unique in MySQL?

Uniqueness in MySQL means we cannot add duplicate records. Now let's see how to create a unique constraint on a column when creating a table.

mysql> create table UniqueConstDemo
- > (
- > name varchar(100) unique
- );

Now, for the column 'Name', we cannot have the same value multiple times.

Insert some records with duplicate values to check for errors.

mysql> insert into UniqueConstDemo values('John');
mysql> insert into UniqueConstDemo values('John');

The following error is visible when the above query is run.

mysql> insert into UniqueConstDemo values('John');
ERROR 1062 (23(000): Duplicate entry 'John' for key 'name'

Inserting different values does not produce an error.

mysql> insert into UniqueConstDemo values('Bob');

Now, let's use the SELECT statement to display all records.

mysql> select *from UniqueConstDemo;

The output is as follows.

+-------+
| name |
+-------+
| Bob |
| John |
+-------+
3 rows in set (0.00 sec)