TechBeamersTechBeamers
  • Python
    • Python Basic
    • Python OOP
    • Python Quiz
    • Python Examples
    • Python Interview
    • Python Selenium
    • Python Advanced
  • Java
    • Java Quiz
    • Java Interview
  • C
  • C#
  • SQL
  • MySQL
  • Selenium
    • Selenium Tutorial
    • TestNG Tutorials
    • Selenium Interview
    • Selenium Quiz
  • Testing
    • Software Testing
    • Manual Testing
    • Software Testing Quiz
    • Testing Interview Questions
  • Agile
  • More
    • Bookmarks
    • Customize
    • About Us
    • Contact
Search
More Tutorials
  • Agile Tutorial
  • Android Tutorial
  • Angular Tutorial
  • Linux Tutorial
  • TestNG Tutorial
Interview Q&A
  • Python Questions
  • Java Questions
  • PHP Questions
  • Web Dev Questions
  • Linux Questions
Coding Quizzes
  • Python Quiz
  • Java Quiz
  • Selenium Quiz
  • HTML CSS Quiz
  • Shell Script Quiz
ยฉ 2023 TechBeamers. All Rights Reserved.
Reading: MySQL UPSERT | INSERT or UPDATE Whichever is Applicable
Share
Notification Show More
Aa
TechBeamersTechBeamers
Aa
  • Agile
  • Android
  • Angular
  • Best IDEs
  • C
  • C#
  • CPP
  • HTML
  • IOT
  • Java
  • Java Interview
  • Java Quiz
  • Linux
  • MySQL
  • PHP Interview
  • Python
  • Python Basic
  • Python Quiz
  • Python Examples
  • Python Advanced
  • Python Interview
  • Python OOP
  • Python Selenium
  • QA Interview
  • Selenium
  • Selenium Quiz
  • Selenium Interview
  • Shell Script Quiz
  • Software Testing
  • Software Testing Quiz
  • SQL Interview
  • Web Development
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Java Interview
    • C# Interview
    • PHP Interview
    • Python Interview
    • QA Interview
    • Selenium Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quiz
    • Java Quiz
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • ShellScript Quiz
    • C/C++ Quiz
  • Bookmarks
    • My Bookmarks
    • My Interests
Follow US
ยฉ 2023 TechBeamers. All Rights Reserved.
TechBeamers > Blog > MySQL Tutorial > MySQL UPSERT | INSERT or UPDATE Whichever is Applicable
MySQL Tutorial

MySQL UPSERT | INSERT or UPDATE Whichever is Applicable

Last updated: 2023/06/04 at 4:10 PM
By Meenakshi Agarwal
Share
7 Min Read
SHARE

This tutorial explains about MySQL UPSERT command with the help of simple examples. An upsert is a smart operation that turns into INSERT or UPDATE whichever is applicable. Also, it is an atomic transaction, which means complete in a single step. Letโ€™s understand โ€“ If a record is new, then UPSERT triggers an INSERT. But, if it already exists, then UPSERT performs an UPDATE.

MySQL provides the ON DUPLICATE KEY UPDATE option to INSERT, which accomplishes this behavior. However, there are other statements like INSERT IGNORE or REPLACE, which can also fulfill this objective. Weโ€™ll discuss and see all these solutions in this post today.

Contents
MySQL UPSERT with Examples1. UPSERT using INSERT IGNORE2. UPSERT using REPLACE3. UPSERT using INSERT with ON DUPLICATE KEY UPDATESummary โ€“ MySQL UPSERT

MySQL UPSERT with Examples

We can imitate MySQL UPSERT in one of these three ways:

1. UPSERT using INSERT IGNORE
2. UPSERT using REPLACE
3. UPSERT using INSERT with ON DUPLICATE KEY UPDATE

However, before you go on reading more, letโ€™s create a sample, and insert some dummy data. Itโ€™ll help us explain the concept through examples.

-- Creating a sample table for testing purpose
CREATE TABLE BLOGPOSTs
    (
        postId INT NOT NULL,
        postTitle VARCHAR(60) PRIMARY KEY,
        postPublished DATE
    );

-- Inserting some data with dummy values
INSERT INTO BLOGPOSTs
    (
        postId, postTitle, postPublished
    )
VALUES
    (1, 'Python Tutorial', '2019-07-21'),
    (2, 'CSharp Tutorial', '2019-07-14'),
    (3, 'MySQL Tutorial', '2019-08-01'),
    (4, 'Java Tutorial', '2019-08-05');

-- Print all rows
SELECT 
    *
FROM
    BLOGPOSTs;

Letโ€™s see each of the above in action below.

1. UPSERT using INSERT IGNORE

When we use INSERT IGNORE for adding a record, it gets through even if there are errors in performing INSERT. So, if the target table already has a row with a matching UNIQUE or PRIMARY key, then INSERT REPLACE would suppress all possible errors.

Moreover, it skips the INSERT operation altogether. Such kind of statement is useful when we need to add a large number of records in one go. And, the table may already have a part of that data inside. Letโ€™s test this behavior with the help of an example.

Here, we are trying to use a duplicate record using the standard MySQL INSERT statement.

-- Inserting duplicate record
INSERT INTO BLOGPOSTs
    (
        postId, postTitle, postPublished
    )
VALUES
    (5, 'Python Tutorial', '2019-08-04');

The above statement fails with the following error:

Duplicate entry 'Python Tutorial' for key 'PRIMARY'

Since the <postTitle> is a primary key, so we canโ€™t have another record having the same value for this field. However, if we do the same operation using the INSERT IGNORE, then it will ignore the error.

Letโ€™s see how it works:

-- Inserting duplicate record
INSERT IGNORE INTO BLOGPOSTs
    (
        postId, postTitle, postPublished
    )
VALUES
    (5, 'Python Tutorial', '2019-08-04');

-- Print all rows
SELECT 
    *
FROM
    BLOGPOSTs;

This time, INSERT wonโ€™t cause any error and SELECT would print all the records.

1	Python Tutorial	2019-07-21
2	CSharp Tutorial	2019-07-14
3	MySQL Tutorial	2019-08-01
4	Java Tutorial	2019-08-05

2. UPSERT using REPLACE

There come situations when we have to replace some rows even if INSERT could fail due to duplicate values of the primary key field. Hence, we should use the REPLACE statement for such cases.

However, if we opt to use REPLACE, then it could result in one of the following outcomes:

  • If we donโ€™t face any error, then REPLACE would behave as regular INSERT command.
  • If a duplicate record exists, then REPLACE would first delete it and perform the INSERT subsequently.

Letโ€™s run our previous test done in #1 again here and observes its result.

-- Replacing duplicate record
REPLACE INTO BLOGPOSTs
    (
        postId, postTitle, postPublished
    )
VALUES
    (5, 'Python Tutorial', '2019-08-04');

-- Print all rows
SELECT 
    *
FROM
    BLOGPOSTs;

The above REPLACE statement added a new row after deleting the duplicate one. Please crosscheck this from the output below.

5	Python Tutorial	2019-08-04
2	CSharp Tutorial	2019-07-14
3	MySQL Tutorial	2019-08-01
4	Java Tutorial	2019-08-05

You can check the below record that appeared after replacing the old one.

-- The old entry was:
1	Python Tutorial	2019-07-21
-- The new entry is:
5	Python Tutorial	2019-08-04

3. UPSERT using INSERT with ON DUPLICATE KEY UPDATE

We saw the two UPSERT commands so far. However, each method had some limitations. The first one INSERT IGNORE was only ignoring the duplicate error, but not making any modification to the table.

The second method, REPLACE, looked a bit more promising. It detected the INSERT error but required the deletion of the row before adding the new record. Hence, we are still wandering for a more refined solution until now.

So, here comes the INSERT โ€ฆ ON DUPLICATE KEY UPDATE statement. It is non-destructive, which means it doesnโ€™t have to drop the duplicate row. Instead, it issues an UPDATE whenever it finds a matching record having the same UNIQUE or PRIMARY KEY value.

Letโ€™s validate the feasibility of the third method with the help of a real example:

-- Updating duplicate record
INSERT INTO BLOGPOSTs
    (
        postId, postTitle, postPublished
    )
VALUES
    (5, 'Python Tutorial', '2019-08-04')
ON DUPLICATE KEY UPDATE
    postId = 5, postTitle = 'Python Tutorial', postPublished = '2019-08-04';

-- Print all rows
SELECT 
    *
FROM
    BLOGPOSTs;

The above MySQL UPSERT command updated the duplicate record. You can crosscheck from the below result set:

5	Python Tutorial	2019-08-04
2	CSharp Tutorial	2019-07-14
3	MySQL Tutorial	2019-08-01
4	Java Tutorial	2019-08-05

The following is the detail of the row that went through modification:

-- The old entry was:
1	Python Tutorial	2019-07-21
-- The new entry is:
5	Python Tutorial	2019-08-04

Summary โ€“ MySQL UPSERT

We hope that after wrapping up this tutorial, you should feel comfortable using the MySQL UPSERT commands. However, you may practice more with examples to gain confidence.

Also, to learn SQL from scratch to depth, do read our step-by-step MySQL tutorial.

You Might Also Like

Create a New User in MySQL with Password

MySQL CURRENT_TIMESTAMP() Function

MySQL vs. PostgreSQL: Point by Point Comparison

Grant Privileges on a Database in MySQL

MySQL FROM_UNIXTIME() Function

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter LinkedIn Email Copy Link
Share
By Meenakshi Agarwal
Follow:
Meenakshi Agarwal is a founder of TechBeamers and has extensive experience in Software Programming and Testing. Here, she aims to share her expertise by providing excellent tutorials for beginners to learn Python, Java, Selenium, C, C++, CSharp, Angular, PHP, JavaScript, Agile, Manual and Automation Testing concepts.
Previous Article MySQL Date and Date Functions Explained MySQL Date and Date Functions
Next Article Python to Find Difference Between Two Lists Python to Find Difference Between Two Lists
Leave a comment Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Latest Tutorials

Learn how to do factorial in python
Factorial Program in Python with Examples
Python Examples June 9, 2023
4 ways to find all possible string permutation in Python
Find All Possible Permutation of a String in Python
Python Examples April 30, 2023
SQL Exercises with Sample Table and Demo Data
SQL Exercises โ€“ Complex Queries
SQL Interview May 10, 2020
//

From Python to Java and everything in between, weโ€™ve got you covered with practical and actionable advice designed to help you level up your coding skills.

Quick Link

  • MY BOOKMARKS
  • MY INTERESTSNew
  • CONTACT US
  • BLOG INDEX

Top Categories

  • AGILE
  • BEST IDEsHot
  • PYTHON
  • SQL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
ยฉ 2023 TechBeamers. All Rights Reserved.
  • Contact Page
  • About Us
  • Terms of Use
  • Privacy Policy
  • Disclaimer
Join Us!

Subscribe to our newsletter and never miss our latest news, podcasts etc..

Loading
Zero spam, Unsubscribe at any time.