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)
Updated on: 2019-10-10T11:50:56+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements