Computer >> Computer tutorials >  >> Programming >> MySQL

Implement INSERT … ON DUPLICATE KEY UPDATE in MySQL


The INSERT ... ON DUPLICATE KEY UPDATE works in a way that if it finds a duplicate unique or primary key, it will perform an UPDATE. The UPDATE is performed only when duplicate values occur.

Let us first create a table −

mysql> create table DemoTable733 (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(100),
   StudentMarks int,
   UNIQUE KEY Un_Name (StudentName)
);
Query OK, 0 rows affected (0.60 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable733(StudentName,StudentMarks) values('John',45) 
ON DUPLICATE KEY UPDATE StudentMarks=86;
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable733(StudentName,StudentMarks) values('Adam',65) 
ON DUPLICATE KEY UPDATE StudentMarks=86;
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable733(StudentName,StudentMarks) values('Carol',75) 
ON DUPLICATE KEY UPDATE StudentMarks=86;
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable733(StudentName,StudentMarks) values('John',45) 
ON DUPLICATE KEY UPDATE StudentMarks=86;
Query OK, 2 rows affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable733;

This will produce the following output -

+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
| 1         | John        | 86           |
| 2         | Adam        | 65           |
| 3         | Carol       | 75           |
+-----------+-------------+--------------+
3 rows in set (0.00 sec)