Adding unique constraint to ALTER TABLE in MySQL


Let us first create a table −

mysql> create table DemoTable1811
     (
     FirstName varchar(20),
     LastName varchar(20)
     );
Query OK, 0 rows affected (0.00 sec)

Here is the query to add index

mysql> alter table DemoTable1811 ADD UNIQUE unique_index_first_last_name(FirstName, LastName);
Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

Insert some records in the table using insert command −

mysql> insert into DemoTable1811 values('John','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1811 values('John','Doe');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1811 values('Adam','Smith');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1811 values('John','Doe');
ERROR 1062 (23000): Duplicate entry 'John-Doe' for key 'unique_index_first_last_name'

Display all records from the table using select statement −

mysql> select * from DemoTable1811;

This will produce the following output −

+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Adam      |    Smith |
| John      |      Doe |
| John      |    Smith |
+-----------+----------+
3 rows in set (0.00 sec)

Updated on: 24-Dec-2019

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements