Coding⏱️ 3 min read📅 2026-06-03

How to Fix: Insert into a MySQL table or update if exists

Insert into a MySQL table or update if exists

Quick Answer: Use the ON DUPLICATE KEY UPDATE clause to achieve this, e.g. INSERT INTO table_name (ID, NAME, AGE) VALUES(1, 'A', 19) ON DUPLICATE KEY UPDATE NAME = 'A', AGE = 19

When trying to insert a new row into a MySQL table, but if a row with the same unique key already exists, you want to update that existing row instead of ignoring the error. This can be frustrating because it seems like the INSERT IGNORE statement should achieve this behavior.

However, using INSERT IGNORE alone is not enough; it will still ignore the error and not update the existing row.

💡 Why You Are Getting This Error

  • The primary reason for this issue is that MySQL uses 'ON DUPLICATE KEY UPDATE' syntax when using INSERT statements with unique keys. This means that if a row already exists in the table, MySQL will insert a new copy of the row and ignore any update attempts.
  • An alternative cause could be a misunderstanding of how INSERT IGNORE works. While it does allow for updates to occur on duplicate rows, it still doesn't actually update the existing row; instead, it skips over it entirely.

🚀 How to Resolve This Issue

Using 'ON DUPLICATE KEY UPDATE' syntax

  1. Step 1: First, make sure you have the correct column names in your INSERT statement. For this example, let's say our table has columns named ID, NAME, and AGE.
  2. Step 2: Next, add a WHERE clause to specify which row(s) should be updated if they already exist. In this case, we want to update only rows with ID = 1.
  3. Step 3: Finally, include the column names you want to update in your INSERT statement's VALUES section. For this example, let's say we want to update NAME and AGE: `INSERT INTO table_name (ID, NAME, AGE) VALUES(1, 'A', 19) ON DUPLICATE KEY UPDATE NAME = VALUES(NAME), AGE = VALUES(AGE);`

Using INSERT IGNORE with a WHERE clause

  1. Step 1: Start by creating an INSERT statement as you normally would. In this case, we want to insert row with ID = 1: `INSERT INTO table_name (ID, NAME, AGE) VALUES(1, 'A', 19);`
  2. Step 2: Add a WHERE clause to specify which row(s) should be updated if they already exist. However, note that using INSERT IGNORE alone will still ignore the error and not update the existing row; you need to manually add the UPDATE statement for this behavior: `INSERT INTO table_name (ID, NAME, AGE) VALUES(1, 'A', 19) ON DUPLICATE KEY UPDATE NAME = VALUES(NAME), AGE = VALUES(AGE);`

🎯 Final Words

By using either the 'ON DUPLICATE KEY UPDATE' syntax or a combination of INSERT IGNORE with a WHERE clause and manual update statement, you can achieve the desired behavior of updating an existing row if it already exists in your MySQL table.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions