
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
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)
- Related Articles
- How to prevent duplicate rows in MySQL INSERT?
- How to prevent MySQL double insert (duplicate entry)?
- How to prevent duplicate JavaScript Variables Declaration?
- Implement INSERT … ON DUPLICATE KEY UPDATE in MySQL
- Implementing INSERT… ON DUPLICATE KEY UPDATE in MySQL
- Correct MySQL INSERT ... ON DUPLICATE KEY syntax?
- How can we use MySQL REPLACE statement to prevent of insertion of duplicate data?
- How to easily insert datetime in MySQL?
- How to avoid inserting duplicate rows in MySQL?
- How to find duplicate value pairs in MySQL?
- How to do a batch insert in MySQL?
- How to insert current date/time in MySQL?
- How to insert a Python object in MySQL?
- How to multiple insert or batch insert at a time in MySQL query?
- How to form a MySQL Conditional Insert?

Advertisements