To prevent duplicate entry, add constraint UNIQUE. Let us first create a table −
mysql> create table DemoTable ( Id int, Name varchar(100) ); Query OK, 0 rows affected (0.79 sec)
Here is the query to prevent MySQL double insert using UNIQUE −
mysql> alter table DemoTable add constraint id_NameUnKey UNIQUE(Id,Name); Query OK, 0 rows affected (0.82 sec) Records: 0 Duplicates: 0 Warnings: 0
Insert records in the table using insert command. When we will try to the same record again, then the “Duplicate entry” error will be visible −
mysql> insert into DemoTable values(11,'John'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(12,'John'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable values(11,'John'); ERROR 1062 (23000): Duplicate entry '11-John' for key 'id_NameUnKey'
Display records from the table using select command −
mysql> select *from DemoTable;
This will produce the following output −
+------+------+ | Id | Name | +------+------+ | 11 | John | | 12 | John | +------+------+ 2 rows in set (0.00 sec)