Implementing INSERT… ON DUPLICATE KEY UPDATE in MySQL

MySQLMySQLi Database

On inserting a new row into a table if the row causes a duplicate in the UNIQUE index or PRIMARY KEY, then expect an error. To fix this, use the ON DUPLICATE KEY UPDATE. On using this in the INSERT statement, the existing row will get updated with the new values.

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Value int
   -> );
Query OK, 0 rows affected (0.61 sec)

Here is the query to create an index −

mysql> create unique index value_index on DemoTable(Value);
Query OK, 0 rows affected (0.77 sec)
Records: 0 Duplicates: 0 Warnings: 0

Insert some records in the table using insert command −

mysql> insert into DemoTable values(40) on duplicate key update Value=Value+1000;
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(50) on duplicate key update Value=Value+1000;
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(40) on duplicate key update Value=Value+1000;
Query OK, 2 rows affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
|    50 |
|  1040 |
+-------+
2 rows in set (0.00 sec)
raja
Published on 12-Dec-2019 10:08:48
Advertisements