Home >Database >Mysql Tutorial >How Can MySQL's INSERT ... ON DUPLICATE KEY UPDATE Simplify Conditional Inserts and Updates?
MySQL’s INSERT ... ON DUPLICATE KEY UPDATE statement: Simplified conditional insertion and update
When using a relational database such as MySQL, you may need to conditionally perform insert or update operations. This occurs when you need to create a new record if it does not exist, or update a record if it already exists. The traditional approach is to use a combination of SELECT and INSERT or UPDATE queries, which can become complex and inefficient.
Fortunately, MySQL provides a more elegant solution: the INSERT ... ON DUPLICATE KEY UPDATE
statement. This versatile command allows you to insert a row if the record does not exist, or update a row if a row with the same key already exists in the table.
Grammar:
<code class="language-sql">INSERT INTO `table_name` (`column_list`) VALUES (`value_list`) ON DUPLICATE KEY UPDATE `column_name` = `new_value`</code>
How it works:
ON DUPLICATE KEY UPDATE
clause specifies which columns should be updated with which of the supplied values. Example:
Consider the following example:
<code class="language-sql">INSERT INTO `usage` (`thing_id`, `times_used`, `first_time_used`) VALUES (4815162342, 1, NOW()) ON DUPLICATE KEY UPDATE `times_used` = `times_used` + 1</code>
thing_id
has a primary key value of 4815162342 that does not exist, insert a new row into the usage
table using the specified value. thing_id
has a primary key value of 4815162342 already exists, update the times_used
column by adding 1 to its current value. Advantages:
INSERT ... ON DUPLICATE KEY UPDATE
provides a concise and clear way to perform insert and update operations using a single query. The above is the detailed content of How Can MySQL's INSERT ... ON DUPLICATE KEY UPDATE Simplify Conditional Inserts and Updates?. For more information, please follow other related articles on the PHP Chinese website!