Oracle SQL Merge Statement
Last Updated on :January 16, 2025
SQL merge will allow you to perform multiple INSERT, UPDATE and DELETE in a single statement.
There are certain situation where you may want to insert a new row into a table or update an existing row depending on whether data already exists or not in the table.
Syntax of merge statement is as follows
Example
In below merge statement we have used product table and product_stg (staging table)
You may receive product related data that contains product information that are already present in system along with new product information those are newly introduced
You can write a SQL merge statement that reads each records from staging table and issue either insert or update on product table depending whether productid already exists or not in product table
Lets discuss how above merge statement executes
- Lines 1-2 : For each row in product_stg table check whether productid exists in product table or not
- Lines 3-7 : If productid already exists in product table then update the matching row in product table using data from product_stg table
- Lines 8-22 : If there is no matching then insert new rows into product table using data from product_stg table