- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements