Using UNIQUE for varchar columns with some conditions in MySQL?

MySQLMySQLi Database

For this, you can use UNIQUE constraint on one or more columns −

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

Let us first create a table −

mysql> create table DemoTable1598
   -> (
   -> EmployeeId int,
   -> EmployeeName varchar(20),
   -> EmployeeCountryName varchar(20)
   -> );
Query OK, 0 rows affected (0.52 sec)

Here is the query to implement UNIQUE on varchar columns −

mysql> alter table DemoTable1598 add unique(EmployeeName,EmployeeCountryName);
Query OK, 0 rows affected (0.55 sec)
Records: 0  Duplicates: 0  Warnings: 0

Insert some records in the table using insert command −

mysql> insert into DemoTable1598 values(101,'Adam','AUS');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1598 values(102,'John','US');
Query OK, 1 row affected (0.64 sec)
mysql> insert into DemoTable1598 values(103,'Adam','US');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable1598 values(104,'Adam','AUS');
ERROR 1062 (23000): Duplicate entry 'Adam-AUS' for key 'EmployeeName'

Display all records from the table using select statement −

mysql> select * from DemoTable1598;

This will produce the following output −

+------------+--------------+---------------------+
| EmployeeId | EmployeeName | EmployeeCountryName |
+------------+--------------+---------------------+
|        101 | Adam         |                AUS  |
|        102 | John         |                US   |
|        103 | Adam         |                US   |
+------------+--------------+---------------------+
3 rows in set (0.00 sec)
raja
Published on 16-Dec-2019 07:21:08
Advertisements