How to prevent duplicate INSERT in MySQL?


For this, you can use UNIQUE INDEX −

alter table yourTableName ADD UNIQUE INDEX(yourColumnName1, yourColumnName2,....N);

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Value1 int,
   -> Value2 int
   -> );
Query OK, 0 rows affected (0.55 sec)

Following is the query to add unique index −

mysql> alter table DemoTable ADD UNIQUE INDEX(Value1, Value2);
Query OK, 0 rows affected (0.54 sec)
Records: 0  Duplicates: 0  Warnings: 0

Insert some records in the table using insert command −

Note − Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.

mysql> insert ignore into DemoTable values(10,20);
Query OK, 1 row affected (0.14 sec)

mysql> insert ignore into DemoTable values(10,20);
Query OK, 0 rows affected, 1 warning (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     10 |   20   |
+--------+--------+
1 row in set (0.00 sec)

Updated on: 30-Jun-2020

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements