- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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)
- Related Articles
- ALTER table by adding AUTOINCREMENT in MySQL?
- Dropping Unique constraint from MySQL table?
- Which statement, other than ALTER TABLE statement, can be used to apply UNIQUE constraint to the field of an existing MySQL table?
- How can we drop UNIQUE constraint from a MySQL table?
- How can we use MySQL ALTER TABLE command for adding comments on columns?
- How can we apply UNIQUE constraint to the field of an existing MySQL table?
- How can we check the indexes created by a UNIQUE constraint on a MySQL table?
- What is MySQL UNIQUE constraint and how can we apply it to the field of a table?
- Alter a table column from VARCHAR to NULL in MySQL
- ALTER TABLE to add a composite primary key in MySQL?
- What happens when we apply NOT NULL constraint, with ALTER TABLE statement, to a column contains NULL values?
- What is the difference between MySQL PRIMARY KEY and UNIQUE constraint?
- How do I add a check constraint to a table in MySQL?
- How can we alter table to add MySQL virtual GENERATED COLUMNS?
- How can we alter table to add MySQL stored GENERATED COLUMNS?

Advertisements