Syntax error Using UNIQUE for varchar columns with some conditions in MySQL?

Using UNIQUE for varchar columns with some conditions in MySQL?



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)
Updated on: 2019-12-16T07:28:14+05:30

210 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements