How to avoid inserting duplicate rows in MySQL?

MySQLMySQLi Database

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)
raja
Published on 01-Apr-2019 07:10:31
Advertisements