INSERT … ON DUPLICATE KEY UPDATE

Description

INSERT ... ON DUPLICATE KEY UPDATE is used to insert data into the database table; if the data already exists, update the data; otherwise, insert new data.

The INSERT INTO statement is a standard statement used to insert data into a database table; the ON DUPLICATE KEY UPDATE statement performs an update operation when there are duplicate records in the table. If a record with the same unique index or primary key exists in the table, use the UPDATE clause to update the corresponding column value; otherwise, use the INSERT clause to insert a new record.

It should be noted that the premise of using this syntax is that a primary key constraint needs to be established in the table to determine whether there are duplicate records. At the same time, both the update operation and the insert operation need to set the corresponding column value. Otherwise, a syntax error will result.

Syntax

  1. > INSERT INTO [db.]table [(c1, c2, c3)] VALUES (v11, v12, v13), (v21, v22, v23), ...
  2. [ON DUPLICATE KEY UPDATE column1 = value1, column2 = value2, column3 = value3, ...];

Examples

  1. CREATE TABLE user (
  2. id INT(11) NOT NULL PRIMARY KEY,
  3. name VARCHAR(50) NOT NULL,
  4. age INT(3) NOT NULL
  5. );
  6. -- Insert a new data; it does not exist, insert the new data
  7. INSERT INTO user (id, name, age) VALUES (1, 'Tom', 18)
  8. ON DUPLICATE KEY UPDATE name='Tom', age=18;
  9. mysql> select * from user;
  10. +------+------+------+
  11. | id | name | age |
  12. +------+------+------+
  13. | 1 | Tom | 18 |
  14. +------+------+------+
  15. 1 row in set (0.01 sec)
  16. -- Increment the age field of an existing record by 1 while keeping the name field unchanged
  17. INSERT INTO user (id, name, age) VALUES (1, 'Tom', 18)
  18. ON DUPLICATE KEY UPDATE age=age+1;
  19. mysql> select * from user;
  20. +------+------+------+
  21. | id | name | age |
  22. +------+------+------+
  23. | 1 | Tom | 19 |
  24. +------+------+------+
  25. 1 row in set (0.00 sec)
  26. -- Insert a new record, and update the name and age fields to the specified values
  27. INSERT INTO user (id, name, age) VALUES (2, 'Lucy', 20)
  28. ON DUPLICATE KEY UPDATE name='Lucy', age=20;
  29. mysql> select * from user;
  30. +------+------+------+
  31. | id | name | age |
  32. +------+------+------+
  33. | 1 | Tom | 19 |
  34. | 2 | Lucy | 20 |
  35. +------+------+------+
  36. 2 rows in set (0.01 sec)

Constraints

Unique key are not currently supported with INSERT ... ON DUPLICATE KEY UPDATE, and since unique key can be null, some unknown errors can occur.