A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/sql/insert-on-duplicate-key-update-in-mysql/ below:

MySQL INSERT ON DUPLICATE KEY UPDATE Statement

MySQL INSERT ON DUPLICATE KEY UPDATE Statement

Last Updated : 23 Jul, 2025

MySQL INSERT ON DUPLICATE KEY UPDATE statement is an extension to the INSERT statement, that if the row being inserted already exists in the table, it will perform a UPDATE operation instead.

INSERT ON DUPLICATE KEY UPDATE in MySQL

INSERT ON DUPLICATE KEY UPDATE statement in MySQL is used to handle duplicate entries on a primary key or unique column. This statement works like a normal INSERT statement until a duplicate value is inserted in a primary key column.

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.

Syntax

MySQL INSERT ON DUPLICATE KEY UPDATE statement syntax is:

INSERT INTO table (column_names)VALUES (values)ON DUPLICATE KEY UPDATE col1 = val1, col2 = val2 ;

Along with the INSERT statement, ON DUPLICATE KEY UPDATE statement defines a list of column & value assignments in case of duplicates.

MySQL INSERT ON DUPLICATE KEY UPDATE Examples

Let's look at some examples of the INSERT ON DUPLICATE KEY UPDATE statement in SQL and understand how it works.

Let us create a table named 'geek_demo' as follows:

follows: geek_demo
(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);

Inserting data into geek_demo :

INSERT INTO geek_demo (name)
VALUES('Neha'), ('Nisha'), ('Sara') ;

Reading data from table :

SELECT id, name
FROM geek_demo;

Output :

id name 1 Neha 2 Nisha 3 Sara

Now, one row will insert into the table.

INSERT INTO geek_demo(name) 
VALUES ('Sneha')
ON DUPLICATE KEY UPDATE name = 'Sneha';

As there was no duplicate, MySQL inserts a new row into the table. The output of the above statement is similar to the output below statement as follows.

INSERT INTO geek_demo(name)
VALUES ('Sneha');

Reading data :

SELECT id, name
FROM geek_demo;

Output :

id name 1 Neha 2 Nisha 3 Sara 4 Sneha

Let us insert a row with a duplicate value in the ID column as follows:

INSERT INTO geek_demo (id, name) 
VALUES (4, 'Mona')
ON DUPLICATE KEY UPDATE name = 'Mona';

Below is the output :

2 row(s) affected

Because a row with id 4 already exists in the geek_demo table, the statement updates the name from Sneha to Mona.

Reading data :

SELECT id, name
FROM geek_demo;

Output :

id name 1 Neha 2 Nisha 3 Sara 4 Mona Important Points About MySQL INSERT ON DUPLICATE KEY UPDATE


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4