
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
Implementing INSERT… ON DUPLICATE KEY UPDATE in MySQL
On inserting a new row into a table if the row causes a duplicate in the UNIQUE index or PRIMARY KEY, then expect an error. To fix this, use the ON DUPLICATE KEY UPDATE. On using this in the INSERT statement, the existing row will get updated with the new values.
Let us first create a table −
mysql> create table DemoTable -> ( -> Value int -> ); Query OK, 0 rows affected (0.61 sec)
Here is the query to create an index −
mysql> create unique index value_index on DemoTable(Value); Query OK, 0 rows affected (0.77 sec) Records: 0 Duplicates: 0 Warnings: 0
Insert some records in the table using insert command −
mysql> insert into DemoTable values(40) on duplicate key update Value=Value+1000; Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(50) on duplicate key update Value=Value+1000; Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(40) on duplicate key update Value=Value+1000; Query OK, 2 rows affected (0.15 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+ | Value | +-------+ | 50 | | 1040 | +-------+ 2 rows in set (0.00 sec)
- Related Articles
- Implement INSERT … ON DUPLICATE KEY UPDATE in MySQL
- Correct MySQL INSERT ... ON DUPLICATE KEY syntax?
- Add constraint for on duplicate key update in MySQL
- Implementing DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP in MySQL
- Update MySQL table on INSERT command with triggers?
- Update table with duplicate ids in MySQL
- How to prevent duplicate INSERT in MySQL?
- Finding Duplicate Rows in MySQL (Composite Key)?
- How to prevent duplicate rows in MySQL INSERT?
- How to update DB2 table with a duplicate primary key?
- How to prevent MySQL double insert (duplicate entry)?
- Use a trigger to stop an insert or update in MySQL?
- Search and update array based on key JavaScript
- Get the new record key ID from MySQL insert query?
- How to insert data to MySQL having auto incremented primary key?

Advertisements