Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
Update Date Field in SQL Server
Next article icon

PL/SQL INSERT ON DUPLICATE KEY UPDATE

Last Updated : 11 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In database management, maintaining data integrity while inserting new records is a common challenge. we may want to insert a new record, but if it already exists based on a unique key, we need to update the existing record. This process is known as "Upsert".

In this article, we will explain how to perform PL/SQL INSERT ON DUPLICATE KEY UPDATE using the MERGE statement. We’ll break down the syntax, explain each key term, and provide real-world examples to illustrate how to handle Upsert efficiently in Oracle databases.

PL/SQL INSERT ON DUPLICATE KEY UPDATE

In Oracle, the MERGE statement can be used to recreate the INSERT ON DUPLICATE KEY UPDATE functionality, which allows for an upsert operation. This means that if a matching record is found based on a condition, it gets updated. If no match is found, a new record is added. The MERGE statement allows both inserting and updating.

Syntax:

MERGE INTO target_table t
USING (SELECT :value1 AS key_column, :value2 AS column_value FROM dual) s
ON (t.key_column = s.key_column)
WHEN MATCHED THEN
UPDATE SET t.column_value = s.column_value
WHEN NOT MATCHED THEN
INSERT (key_column, column_value)
VALUES (s.key_column, s.column_value);

Key Terms:

  • MERGE INTO target_table: The table where the operation is being performed.
  • USING (SELECT ... FROM dual): Provides the source data for comparison.
  • ON (t.key_column = s.key_column): Specifies the condition for matching records.
  • WHEN MATCHED: Defines the update operation if the condition matches.
  • WHEN NOT MATCHED: Defines the insert operation if no match is found.

Examples of PL/SQL INSERT ON DUPLICATE KEY UPDATE

Let's explain examples to demonstrate how to implement this approach in Oracle databases. We will first examine how to update an existing record if a matching entry is found. Then, we will see how to insert a new record when no match exists, using the MERGE statement for both scenarios.

Example 1: Using MERGE for Upsert

Let's assume we have a table called Products that stores product information. If a product with the same product_id already exists, we want to update the price. If it does not exist, a new record should be inserted.

Query:

 -- Create the Products table
CREATE TABLE Products (
product_id INT PRIMARY KEY, -- Primary key for product identification
product_name VARCHAR2(50), -- Name of the product
price NUMBER(10, 2) -- Price of the product
);

-- Inserting initial data
INSERT INTO Products (product_id, product_name, price)
VALUES (101, 'Laptop', 1200); -- Insert a new product with price 1200

-- Upsert operation using MERGE
MERGE INTO Products t
USING (SELECT 101 AS product_id, 'Laptop' AS product_name, 1250 AS price FROM dual) s
ON (t.product_id = s.product_id) -- Condition to check if the product exists
WHEN MATCHED THEN
UPDATE SET t.price = s.price -- Update the price if the product exists
WHEN NOT MATCHED THEN
INSERT (product_id, product_name, price)
VALUES (s.product_id, s.product_name, s.price); -- Insert new product if it does not exist

Output:

product_idproduct_nameprice
101Laptop1250

Explanation:

  • The MERGE statement checks if the product with product_id = 101 already exists.
  • Since the product exists, it updates the price from 1200 to 1250.
  • If the product does not exist, the WHEN NOT MATCHED clause would insert a new row.

Example 2: Inserting a New Record

In this example, we perform an INSERT ON DUPLICATE KEY UPDATE operation where the product ID does not exist in the table, leading to an insert operation. Hence, the operation will insert a new record.

Query:

 -- Upsert operation using MERGE for a new product
MERGE INTO Products t
USING (SELECT 102 AS product_id, 'Smartphone' AS product_name, 700 AS price FROM dual) s
ON (t.product_id = s.product_id) -- Condition to check if the product exists
WHEN MATCHED THEN
UPDATE SET t.price = s.price -- Update the price if the product exists
WHEN NOT MATCHED THEN
INSERT (product_id, product_name, price)
VALUES (s.product_id, s.product_name, s.price); -- Insert new product if it does not exist

Output:

product_idproduct_nameprice
101Laptop1250
102Smartphone700

Explanation:

  • Since no product with product_id = 102 exists, a new row is inserted with the details of the smartphone.
  • Since no product with that ID exists, the WHEN NOT MATCHED clause inserts the new product with the values provided.

Another Approach: Conditional INSERT and UPDATE

If we don't want to use the MERGE statement, another method to perform an upsert operation is by combining INSERT and UPDATE statements conditionally using PL/SQL logic.

Query:

BEGIN
-- Attempt to update the price for the existing product
UPDATE Products
SET price = 1500
WHERE product_id = 101; -- Condition to check if the product exists

-- Check if the update affected any rows
IF SQL%ROWCOUNT = 0 THEN
-- Insert a new product if no rows were updated
INSERT INTO Products (product_id, product_name, price)
VALUES (101, 'Laptop', 1500); -- Insert new product if it does not exist
END IF;
END;

Explanation:

  • The UPDATE statement tries to update the price of the product.
  • If no rows are affected (SQL%ROWCOUNT = 0), an INSERT statement is executed to add a new row.

Conclusion

Using the PL/SQL MERGE statement for INSERT ON DUPLICATE KEY UPDATE operations is a powerful way to maintain data integrity and ensure database consistency. The MERGE statement efficiently handles both inserts and updates, making it a valuable tool for managing large datasets and avoiding duplicates.


Next Article
Update Date Field in SQL Server

A

abhay94517
Improve
Article Tags :
  • Databases
  • PL/SQL

Similar Reads

  • How to Find Duplicate Rows in PL/SQL
    Finding duplicate rows is a widespread requirement when dealing with database analysis tasks. Duplicate rows often create problems in analyzing tasks. Detecting them is very important. PL/SQL is a procedural extension for SQL. We can write custom scripts with the help of PL/SQL and thus identifying
    5 min read
  • Python SQLite - Insert Data
    In this article, we will discuss how can we insert data in a table in the SQLite database from Python using the sqlite3 module. The SQL INSERT INTO statement of SQL is used to insert a new row in a table. There are two ways of using the INSERT INTO statement for inserting rows: Only values: The firs
    3 min read
  • Update Date Field in SQL Server
    The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using the UPDATE statements as per our requirement. With this article, we will learn how to Update the Date Field in SQL Server. In this article, we w
    2 min read
  • MySQL Insert Date Time
    In today's world, working with data is now a data-to-data activity, so therefore managing data with proper data and time is also crucial. MySQL provides functionalities to handle data and time properly in the database. Understanding how to insert data and time into MySQL database with functions prov
    4 min read
  • PL/SQL Insert Dates
    When managing databases, handling date and time data accurately is important. Date fields are frequently used for storing important information such as user birth dates, product release dates, and event timelines. Oracle PL/SQL provides robust support for date operations, ensuring accurate data stor
    4 min read
  • SQLite – INSERT IF NOT EXISTS ELSE UPDATE
    SQLite is a popular choice for embedded database applications due to its lightweight nature and ease of use. One common scenario in SQLite is the need to insert a row into a table if it does not already exist and update it if it does. In this article, We will explore how to achieve this efficiently
    4 min read
  • When to Use ON UPDATE CASCADE in PL/SQL?
    In Oracle PL/SQL, managing the update of related records in child tables can be challenging, especially when dealing with complex data relationships. The ON UPDATE CASCADE option in Oracle provides a powerful solution to automate the update of child records whenever the corresponding parent record i
    4 min read
  • PL/SQL Insert DateTimes
    In PL/SQL, handling date and time values is a common requirement, whether we are working with databases that store transaction times, schedule events, or track user activities. Understanding how to insert these values correctly is crucial for accurate data management and retrieval. In this article,
    4 min read
  • PL/SQL Cursor Update
    PL/SQL stands for Procedural Language/Structured Query Language. It has block structure programming features. In Oracle PL/SQL, cursors play a vital role in managing and processing query results. Among the various types of cursors, updatable cursors stand out for their ability to fetch data and modi
    5 min read
  • How to Find Duplicate Records in SQL?
    To find duplicate records in SQL, we can use the GROUP BY and HAVING clauses. The GROUP BY clause allows us to group values in a column, and the COUNT function in the HAVING clause shows the count of the values in a group. Using the HAVING clause with a condition of COUNT(*) > 1, we can identify
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences