MySQL UNIQUE declaration to avoid inserting duplicate values?



Following is the declaration for a UNIQUE clause in MySQL −

create table yourTableName (    yourColumnName1 dataType,    yourColumnName2 dataType,    UNIQUE(yourColumnName1),    UNIQUE(yourColumnName1) );

Let us first create a table −

mysql> create table DemoTable (    Value int,    Value2 int,    UNIQUE(Value),    UNIQUE(Value2) ); Query OK, 0 rows affected (13.98 sec)

Insert some records in the table using insert command. Here, duplicate records won’t insert because we have used UNIQUE above −

mysql> insert into DemoTable values(10,20) ; Query OK, 1 row affected (0.32 sec) mysql> insert into DemoTable values(10,30); ERROR 1062 (23000): Duplicate entry '10' for key 'Value' mysql> insert into DemoTable values(40,20); ERROR 1062 (23000): Duplicate entry '20' for key 'Value2' mysql> insert into DemoTable values(60,70); Query OK, 1 row affected (1.37 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+--------+ | Value | Value2 | +-------+--------+ | 10 | 20 | | 60 | 70 | +-------+--------+ 2 rows in set (0.00 sec)
Updated on: 2019-09-30T06:46:13+05:30

262 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements