How to make a pair of columns unique in MySQL?

MySQLMySQLi Database

To make a pair of columns unique, use UNIQUE with ALTER TABLE command. Following is the syntax −

alter table yourTableName add unique yourUniqueName(yourColumnName1,yourColumnName2,...N);

Let us first create a table −

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFirstName varchar(100),
   StudentLastName varchar(100),
   StudentAge int,
   StudentPhoneNumber varchar(20)
);
Query OK, 0 rows affected (0.81 sec)

Following is the query to make a pair of unique columns in MySQL −

mysql> alter table DemoTable add unique DemoTable_unique_StudentFirstName_StudentPhoneNumber(StudentFirstName,StudentPhoneNumber);
Query OK, 0 rows affected (0.40 sec)
Records: 0 Duplicates: 0 Warnings: 0

Insert some records in the table using insert command −

mysql> insert into DemoTable(StudentFirstName,StudentLastName,StudentAge,StudentPhoneNumber) values('John','Doe',21,'9878567878');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName,StudentAge,StudentPhoneNumber) values('John','Smith',23,'7654674545');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentFirstName,StudentLastName,StudentAge,StudentPhoneNumber)
values('John','Brown',21,'9878567878');
ERROR 1062 (23000): Duplicate entry 'John-9878567878' for key 'DemoTable_unique_StudentFirstName_StudentPhoneNumber'

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+------------------+-----------------+------------+--------------------+
| StudentId | StudentFirstName | StudentLastName | StudentAge | StudentPhoneNumber |
+-----------+------------------+-----------------+------------+--------------------+
|         1 | John             | Doe             | 21         | 9878567878         |
|         2 | John             | Smith           | 23         | 7654674545         |
+-----------+------------------+-----------------+------------+--------------------+
2 rows in set (0.00 sec)
raja
Published on 25-Sep-2019 12:16:46
Advertisements