How to insert only those records that does not exist in a MySQL table?


To insert when a record does not exist, set the column as UNIQUE INDEX. Let us first create a table −

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

Following is the query to create unique index to insert record which does not exist in the ‘FirstName’ column −

mysql> CREATE UNIQUE INDEX index_on_FirstName ON DemoTable(FirstName);
Query OK, 0 rows affected (0.56 sec)
Records: 0 Duplicates: 0 Warnings: 0

Insert some records in the table using insert command. Now here you can check the insert command inserts only those record which does not exist −

mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.07 sec)

mysql> insert into DemoTable(FirstName) values('Chris');
ERROR 1062 (23000): Duplicate entry 'Chris' for key 'index_on_FirstName'
mysql>
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(FirstName) values('Mike');
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(FirstName) values('Robert');
ERROR 1062 (23000): Duplicate entry 'Robert' for key 'index_on_FirstName'
mysql>

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | Chris     |
|  2 | Robert    |
|  3 | Mike      |
+----+-----------+
3 rows in set (0.00 sec)

Updated on: 30-Jul-2019

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements