Inorder to perform this you can prefer using the MySQL INSERT ON DUPLICATE KEY UPDATE statement
.
The INSERT ON DUPLICATE KEY UPDATE
is a MySQL extension to the INSERT statement. If you specify the ON DUPLICATE KEY UPDATE
option in the INSERT statement and the new row causes a duplicate value in the UNIQUE
or PRIMARY KEY
index, MySQL performs an update to the old row based on the new values.
The syntax of INSERT ON DUPLICATE KEY UPDATE
statement is as follows:
INSERT INTO table(column_list)
VALUES(value_list)
ON DUPLICATE KEY UPDATE column_1 = new_value_1, column_2 = new_value_2, …;
The only addition to the INSERT statement is the ON DUPLICATE KEY UPDATE clause where you specify a list of comma-separated column assignments.
MySQL returns the number of affected rows based on the action it performed.
- If MySQL inserts the row as a new row, the number of affected row is 1.
- If MySQL updates the current row, the number of affected rows is 2.
- In case MySQL updates the current row with its current values, the number of affected rows is 0.
Insert Statement:
INSERT INTO devices(name) VALUES ('Printer') ON DUPLICATE KEY UPDATE name = 'Printer';
This is a Insert statement since the devices table does not contain the Printer
value and hence it will Insert it.
Update Statement:
INSERT INTO devices(id,name) VALUES (4,'Printer') ON DUPLICATE KEY UPDATE name = 'Server';
This will update the table since the already the Printer is present so that it will update the table values as Server.