Home > Database > Mysql Tutorial > How to Insert or Update Rows in MySQL Using INSERT...ON DUPLICATE KEY UPDATE?

How to Insert or Update Rows in MySQL Using INSERT...ON DUPLICATE KEY UPDATE?

Mary-Kate Olsen
Release: 2025-01-24 02:32:09
Original
636 people have browsed it

How to Insert or Update Rows in MySQL Using INSERT...ON DUPLICATE KEY UPDATE?

Handling Duplicate Key Conflicts in MySQL: INSERT...ON DUPLICATE KEY UPDATE

When inserting data into a MySQL table with a unique key constraint, a conflict arises if a duplicate key is encountered. The INSERT...ON DUPLICATE KEY UPDATE statement elegantly solves this problem by allowing you to either insert a new row or update an existing one based on the unique key.

Let's consider a table with a unique 'ID' column. If you attempt to insert a row with an existing ID, a standard INSERT statement will fail. The INSERT...ON DUPLICATE KEY UPDATE provides a solution.

Example Scenario:

Imagine you're adding data to a users table:

INSERT INTO users (ID, Name, Age) VALUES (1, "Bob", 30);

If a user with ID = 1 already exists, this query will fail.

The Solution:

Use INSERT...ON DUPLICATE KEY UPDATE:

INSERT INTO users (ID, Name, Age) VALUES (1, "Bob", 30) ON DUPLICATE KEY UPDATE Name = "Bob", Age = 30;

Explanation:

  • The INSERT part specifies the data to be inserted.
  • ON DUPLICATE KEY UPDATE dictates the update action if a duplicate key is found.
  • In this example, if ID = 1 exists, the Name and Age columns will be updated with the provided values. If ID = 1 doesn't exist, a new row is inserted.

This approach ensures data integrity while preventing errors caused by duplicate key insertions. It's a concise and efficient way to manage data updates in MySQL.

The above is the detailed content of How to Insert or Update Rows in MySQL Using INSERT...ON DUPLICATE KEY UPDATE?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template