INSERT ... ON DUPLICATE KEY UPDATE inserts a new row when no unique-key conflict occurs and updates the existing row when an PRIMARY KEY or other UNIQUE key conflicts.
INSERT INTO student3 (id, name, class, social, science, math)
VALUES (2, 'Max Ruin', 'Three', 86, 57, 86);
INSERT INTO student3 (id, name, class, social, science, math)
VALUES (2, 'Max Ruin', 'Three', 86, 57, 86) AS new
ON DUPLICATE KEY UPDATE
social = new.social,
science = new.science,
math = new.math;
The row alias new represents the values that would have been inserted. Current MySQL recommends this form instead of the older VALUES(column) form.
INSERT INTO student3 (id, name, class, social, science, math)
VALUES
(2, 'Max Ruin', 'Three', 86, 57, 86),
(3, 'Arnold', 'Three', 56, 41, 76),
(4, 'Krish Star', 'Four', 62, 52, 72),
(5, 'John Mike', 'Four', 62, 82, 92),
(6, 'Alex John', 'Four', 58, 93, 83),
(7, 'My John Rob', 'Fifth', 79, 64, 74),
(8, 'Asruid', 'Five', 89, 84, 94),
(9, 'Tes Qry', 'Six', 77, 61, 71),
(10, 'Big John', 'Four', 56, 44, 56) AS new
ON DUPLICATE KEY UPDATE
social = new.social,
science = new.science,
math = new.math;
INSERT INTO student3 (id, name, class, social, science, math)
VALUES
(2, 'Max Ruin', 'Three', 86, 57, 86),
(3, 'Arnold', 'Three', 56, 41, 76),
(4, 'Krish Star', 'Four', 62, 52, 72),
(5, 'John Mike', 'Four', 62, 82, 92),
(6, 'Alex John', 'Four', 58, 93, 83),
(7, 'My John Rob', 'Fifth', 79, 64, 74),
(8, 'Asruid', 'Five', 89, 84, 94),
(9, 'Tes Qry', 'Six', 77, 61, 71),
(10, 'Big John', 'Four', 56, 44, 56),
(11, 'New Name', 'Five', 75, 78, 52) AS new
ON DUPLICATE KEY UPDATE
social = new.social,
science = new.science,
math = new.math;
Rows whose key already exists are updated; ID 11 is inserted if it is new.
VALUES(column) in the update clause. MySQL has deprecated that use; row aliases are the current form.Download the student3 SQL dump
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
13-10-2021 | |
| really good explanation! Thanks! | |
13-10-2021 | |
| Really good article for begineers | |