The UPDATE statement is given so that older fields can be updated to new value. If your older values are the same as your new ones, why would you need to update it in any case?

For eg. if your columns a to g are already set as 2 to 8; there would be no need to re-update it.

Alternatively, you can use:

INSERT INTO table (id,a,b,c,d,e,f,g)
VALUES (1,2,3,4,5,6,7,8) 
ON DUPLICATE KEY
    UPDATE a=a, b=b, c=c, d=d, e=e, f=f, g=g;

To get the id from LAST_INSERT_ID; you need to specify the backend app you're using for the same.

For LuaSQL, a conn:getlastautoid() fetches the value.

Answer from hjpotter92 on Stack Overflow
Top answer
1 of 9
108

The UPDATE statement is given so that older fields can be updated to new value. If your older values are the same as your new ones, why would you need to update it in any case?

For eg. if your columns a to g are already set as 2 to 8; there would be no need to re-update it.

Alternatively, you can use:

INSERT INTO table (id,a,b,c,d,e,f,g)
VALUES (1,2,3,4,5,6,7,8) 
ON DUPLICATE KEY
    UPDATE a=a, b=b, c=c, d=d, e=e, f=f, g=g;

To get the id from LAST_INSERT_ID; you need to specify the backend app you're using for the same.

For LuaSQL, a conn:getlastautoid() fetches the value.

2 of 9
55

There is a MySQL specific extension to SQL that may be what you want - REPLACE INTO

However it does not work quite the same as 'ON DUPLICATE UPDATE'

  1. It deletes the old row that clashes with the new row and then inserts the new row. So long as you don't have a primary key on the table that would be fine, but if you do, then if any other table references that primary key

  2. You can't reference the values in the old rows so you can't do an equivalent of

    INSERT INTO mytable (id, a, b, c) values ( 1, 2, 3, 4) 
    ON DUPLICATE KEY UPDATE
    id=1, a=2, b=3, c=c + 1;
    

I'd like to use the work around to get the ID to!

That should work — last_insert_id() should have the correct value so long as your primary key is auto-incrementing.

However as I said, if you actually use that primary key in other tables, REPLACE INTO probably won't be acceptable to you, as it deletes the old row that clashed via the unique key.

Someone else suggested before you can reduce some typing by doing:

INSERT INTO `tableName` (`a`,`b`,`c`) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE `a`=VALUES(`a`), `b`=VALUES(`b`), `c`=VALUES(`c`);
🌐
MySQL
dev.mysql.com › doc › refman › 8.4 › en › insert-on-duplicate.html
MySQL :: MySQL 8.4 Reference Manual :: 15.2.7.2 INSERT ... ON DUPLICATE KEY UPDATE Statement
In assignment value expressions in the ON DUPLICATE KEY UPDATE clause, you can use the VALUES(col_name) function to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE statement. In other words, VALUES(col_name) in the ON DUPLICATE KEY UPDATE clause refers to the value of col_name that would be inserted, had no duplicate-key conflict occurred.
Discussions

mysql - UPDATE vs INSERT INTO... ON DUPLICATE KEY UPDATE - Database Administrators Stack Exchange
Alright so I have this table in which until now I was using the following queries to UPDATE else do an INSERT: $db->query("UPDATE ulogs SET invalid = invalid + 1 WHERE uid = 666 AND date = '201... More on dba.stackexchange.com
🌐 dba.stackexchange.com
MySQL - On duplicate key update
Describe the issue/error/question Hi All, I’m trying to get data from an API endpoint, and store it in MYSQL This works, but there is a primary key on my table “id” so I’d like to do “on duplicate key update” but when i try to do this, it errors with invalid SQL In the preview window ... More on community.n8n.io
🌐 community.n8n.io
0
0
February 24, 2023
mysql - INSERT ON DUPLICATE KEY UPDATE - How can I get my query to work? - Database Administrators Stack Exchange
I have a "votes" table where users can submit a score for a product. I have a second "stats" table which stores the average scores and total vote counts for each product that has More on dba.stackexchange.com
🌐 dba.stackexchange.com
mysql - Is there a way to use ON DUPLICATE KEY to Update all that I wanted to insert? - Stack Overflow
I know that you can use ON DUPLICATE KEY UPDATE to update a certain value if there is a record for that key already, I can do this: INSERT INTO `tableName` (`a`,`b`,`c`) VALUES (1, 2, 3) ON DUPLI... More on stackoverflow.com
🌐 stackoverflow.com
🌐
MariaDB
mariadb.com › docs › server › reference › sql-statements › data-manipulation › inserting-loading-data › insert-on-duplicate-key-update
INSERT ON DUPLICATE KEY UPDATE | Server | MariaDB Documentation
January 28, 2026 - INSERT ... ON DUPLICATE KEY UPDATE (often called "upsert") is a MariaDB/MySQL extension to the INSERT statement that, if it finds a duplicate unique or primary key, will instead perform an UPDATE.
🌐
Prisma
prisma.io › dataguide › mysql › inserting-and-modifying-data › insert-on-duplicate-key-update
ON DUPLICATE KEY UPDATE to upsert and modify data in MySQL
The ON DUPLICATE KEY UPDATE clause allows us to do this: INSERT INTO director (id, name) VALUES (3, 'susan') ... MySQL considers an ON DUPLICATE KEY UPDATE where an update occurs to the existing row as two rows affected.
🌐
Bennadel
bennadel.com › blog › 4590-conditionally-updating-columns-when-using-on-duplicate-key-update-in-mysql.htm
Conditionally Updating Columns When Using ON DUPLICATE KEY UPDATE In MySQL
February 1, 2024 - In this SQL statement, I'm using the ON DUPLICATE KEY UPDATE clause in order to update any existing row with a matching email address (which, remember, is being used as the primary key).
🌐
MySQL
dev.mysql.com › doc › refman › 8.0 › en › insert-on-duplicate.html
MySQL :: MySQL 8.0 Reference Manual :: 15.2.7.2 INSERT ... ON DUPLICATE KEY UPDATE Statement
January 13, 2022 - In assignment value expressions in the ON DUPLICATE KEY UPDATE clause, you can use the VALUES(col_name) function to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE statement. In other words, VALUES(col_name) in the ON DUPLICATE KEY UPDATE clause refers to the value of col_name that would be inserted, had no duplicate-key conflict occurred.
🌐
Oracle
docs.oracle.com › cd › E17952_01 › mysql-5.7-en › insert-on-duplicate.html
13.2.5.2 INSERT ... ON DUPLICATE KEY UPDATE Statement
February 9, 2026 - With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag to the mysql_real_connect() C API function when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values.
Find elsewhere
🌐
MySQL Tutorial
mysqltutorial.org › home › mysql basics › mysql insert on duplicate key update statement
MySQL INSERT ON DUPLICATE KEY UPDATE Statement
December 27, 2023 - INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...) AS new_data -- Row alias ON DUPLICATE KEY UPDATE column1 = new_data.column1, column2 = new_data.column2 + 1;Code language: SQL (Structured Query Language) (sql) MySQL also allows you to assign aliases to columns to avoid ambiguity, especially with long column names:
🌐
TutorialsPoint
tutorialspoint.com › mysql › mysql-insert-on-duplicate-update.htm
MySQL − Insert on Duplicate Key Update
sql = "INSERT INTO my_table (column1, column2, ...) VALUES (value1, value2), (value3, value4), ... ON DUPLICATE KEY UPDATE column1 = value1, column2 = value2, ..."; con.query(sql); To update the duplicate row with new one in MySQL table through a Java program, we use the DUPLICATE KEY UPDATE along with INSERT statement using the JDBC function executeUpdate() as −
🌐
GeeksforGeeks
geeksforgeeks.org › mysql › insert-on-duplicate-key-update-in-mysql
MySQL INSERT ON DUPLICATE KEY UPDATE Statement - GeeksforGeeks
July 23, 2025 - When a duplicate value is entered in the primary key column, it raises an error. But the ON DUPLICATE KEY UPDATE clause handles this error by updating the row of the Primary key column. MySQL INSERT ON DUPLICATE KEY UPDATE statement syntax is:
🌐
n8n
community.n8n.io › questions
MySQL - On duplicate key update - Questions - n8n Community
February 24, 2023 - Describe the issue/error/question Hi All, I’m trying to get data from an API endpoint, and store it in MYSQL This works, but there is a primary key on my table “id” so I’d like to do “on duplicate key update” but when i try to do this, it errors with invalid SQL In the preview window ...
🌐
Plus2Net
plus2net.com › sql_tutorial › sql_update-on-duplicate-key.php
Update multiple records by using ON DUPLICATE KEY UPDATE in MySQL
February 5, 2000 - INSERT INTO `student3` (`id`, `name`, ... (10, 'Big John', 'Four', 56, 44, 56) ON DUPLICATE KEY UPDATE social=values(social),science=values(science),math=values(math); Above query will update 9 records with new data....
🌐
LinkedIn
linkedin.com › pulse › understanding-mysql-insert-duplicate-update-upsert-bilal-usean
Understanding MySQL INSERT ON DUPLICATE UPDATE OR UPSERT
September 15, 2023 - Here's where "INSERT ON DUPLICATE UPDATE" comes to the rescue. With this feature, you can achieve your goal in a single SQL statement. Here's the basic syntax: INSERT INTO employees (employee_id, name, department) VALUES (123, 'John Doe', 'Marketing') ON DUPLICATE KEY UPDATE name = 'John Doe', department = 'Marketing';
Top answer
1 of 2
3

You can only make alterations in the context of one conflicting row in the ON DUPLICATE KEY area. Further, this is, as far as I know, a property of the INSERT statement.

What you need is a simple ledger where you record the additions and subtractions from a balance, then tabulate those either manually or using triggers.

For instance, the simplest approach is:

INSERT INTO points_adjustments (boardId_from, boardId_to, points)
  VALUES (?, ?, ?)

This might be more easily represented as a pair of entries:

INSERT INTO points_adjustments (boardId, points)
  VALUES (?, ?)

You'd add one entry for +n points, and a matching one for -n. At any time you can get a balance using SUM(points). You could wrap this up in a VIEW to make retrieval easier, or if you want, denormalize the sums into a column of another table using a trigger.

A simple trigger would issue the following statement for each affected boardId:

INSERT INTO balances (boardId, points) VALUES (?, ?)
  ON DUPLICATE KEY SET points=points+VALUES(points)

This avoids key collisions in the first place and provides an auditable record of the transactions that occurred.

In any case, to do all of this automatically you'd probably have to use a trigger.

3rd party edit

From the docs INSERT ... ON DUPLICATE KEY UPDATE Statement

In general, you should try to avoid using an ON DUPLICATE KEY UPDATE clause on tables with multiple unique indexes.

2 of 2
0

No. You can't delete a record upon constraint violation in MySQL. You could possibly do a before update trigger that checks for an impending constraint violation, but even then (as of 5.1) you can't modify that same table's data (which would likely cause an endless loop in this case anyway).

Only halfway finished before Tadman's answer. I like his idea, personally.

🌐
jOOQ
jooq.org › doc › latest › manual › sql-building › sql-statements › insert-statement › insert-on-duplicate-key
The ON DUPLICATE KEY UPDATE clause of the INSERT statement
MERGE INTO AUTHOR USING ( SELECT 3, 'X' FROM (VALUES (1)) AS dual (dual) ) t (ID, LAST_NAME) ON AUTHOR.ID = t.ID WHEN MATCHED THEN UPDATE SET AUTHOR.LAST_NAME = 'X' WHEN NOT MATCHED THEN INSERT (ID, LAST_NAME) VALUES ( t.ID, t.LAST_NAME ) INSERT INTO AUTHOR (ID, LAST_NAME) VALUES ( 3, 'X' ) AS excluded ON DUPLICATE KEY UPDATE AUTHOR.LAST_NAME = 'X'