Making an existing field Unique in MySQL?

MySQLMySQLi Database

Unique in MySQL means we cannot add duplicate records. Let us now see how to create a unique constraint in the column at the time of creating a table.

mysql> create table UniqueConstDemo
- > (
- > name varchar(100) unique
- > );
Query OK, 0 rows affected (0.72 sec)

Now, we cannot have same value more than once for column ‘name’.

Inserting some records with duplicate values to check the error.

mysql> insert into UniqueConstDemo values('John');
Query OK, 1 row affected (0.19 sec)

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

On running the above query, the following error is visible.

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

Inserting different values won’t give an error.

mysql> insert into UniqueConstDemo values('Bob');
Query OK, 1 row affected (0.11 sec)

Now, let us display all the records with the help of SELECT statement.

mysql> select *from UniqueConstDemo;

The following is the output.

+-------+
| name  |
+-------+
| Bob   |
| John  |
+-------+
3 rows in set (0.00 sec)
raja
Published on 20-Nov-2018 12:26:35
Advertisements