Correct MySQL INSERT ... ON DUPLICATE KEY syntax?

MySQLMySQLi Database

The syntax is as follows −

insert into yourTableName values(yourValue1,yourValue2,..N)
on duplicate key update yourColumnName1=yourValue1,yourColumnName2=yourValue2,....N;

Let us first create a table −

mysql> create table DemoTable1539
   -> (
   -> EmployeeName varchar(20),
   -> EmployeeSalary int,
   -> UNIQUE KEY(EmployeeName)
   -> );
Query OK, 0 rows affected (0.62 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1539 values('Chris',4500) on duplicate key update EmployeeName='Robert',EmployeeSalary=8500;
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1539 values('David',5500) on duplicate key update EmployeeName='Robert',EmployeeSalary=8500;
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1539 values('Chris',4500) on duplicate key update EmployeeName='Robert',EmployeeSalary=8500;
Query OK, 2 rows affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1539;

This will produce the following output −

+--------------+----------------+
| EmployeeName | EmployeeSalary |
+--------------+----------------+
| Robert       |           8500 |
| David        |           5500 |
+--------------+----------------+
2 rows in set (0.00 sec)
raja
Published on 12-Dec-2019 10:23:03
Advertisements