How to avoid inserting duplicate rows in MySQL?


To avoid inserting duplicate rows in MySQL, you can use UNIQUE(). The syntax is as follows −

ALTER TABLE yourTableName ADD UNIQUE(yourColumnName1,yourColumnName2,...N);

To understand the above syntax, let us create a table. 

The query to create a table is as follows −

mysql> create table avoidInsertingDuplicateRows
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> FirstValue int,
   -> SecondValue int
   -> );
Query OK, 0 rows affected (0.53 sec)

Now check the description of table using desc command. 

The query is as follows −

mysql> desc avoidInsertingDuplicateRows;

Sample The following is The output −

+-------------+---------+------+-----+---------+----------------+
| Field       | Type    | Null | Key | Default | Extra          |
+-------------+---------+------+-----+---------+----------------+
| Id          | int(11) | NO   | PRI | NULL    | auto_increment |
| FirstValue  | int(11) | YES  |     | NULL    |                |
| SecondValue | int(11) | YES  |     | NULL    |                |
+-------------+---------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

Here is the query to avoid inserting duplicate rows in MySQL. We will set it with the insert command to insert records in the table −

mysql> insert into avoidInsertingDuplicateRows(FirstValue,SecondValue) values(10,20);
Query OK, 1 row affected (0.24 sec)
mysql> insert into avoidInsertingDuplicateRows(FirstValue,SecondValue) values(10,20);
ERROR 1062 (23000): Duplicate entry '10-20' for key 'FirstValue'

Display all records from the table using select statement. 

The query is as follows −

mysql> select *from avoidInsertingDuplicateRows;

Here is the output −

+----+------------+-------------+
| Id | FirstValue | SecondValue |
+----+------------+-------------+
| 1  | 10         | 20          |
+----+------------+-------------+
1 row in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements