How to prevent duplicate rows in MySQL INSERT?


For this, you need to use UNIQUE KEY for the column. Let us first create a table −

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   FirstName varchar(30),
   UNIQUE KEY(FirstName)
);
Query OK, 0 rows affected (1.76 sec)

Insert some records in the table using insert command. Now, we are also inserting duplicate records like “David”, but it won’t get inserted twice, since we have set the column as UNIQUE KEY −

mysql> insert ignore into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.42 sec)
mysql> insert ignore into DemoTable(FirstName) values('David');
Query OK, 1 row affected (0.12 sec)
mysql> insert ignore into DemoTable(FirstName) values('Chris');
Query OK, 0 rows affected, 1 warning (0.17 sec)
mysql> insert ignore into DemoTable(FirstName) values('Sam');
Query OK, 1 row affected (0.11 sec)
mysql> insert ignore into DemoTable(FirstName) values('David');
Query OK, 0 rows affected, 1 warning (0.07 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | Chris     |
|  2 | David     |
|  4 | Sam       |
+----+-----------+
3 rows in set (0.00 sec)
raja
Published on 10-Oct-2019 15:19:51
Advertisements