SQL MERGE Statement – INSERT, UPDATE, DELETE at once

By | 13. 12. 2019

SQL MERGE command is an advanced way of comparing data in two tables (Source and Destination). We compare records and based on match (or difference) we execute UPDATE, INSERT or DELETE according to the result of table comparison.

We will use this mainly with data sync between objects/systems or with ETL processes in environments like data warehouse or data mart.

Syntax:

MERGE Target_Table AS TARGET
USING Source_Table AS SOURCE
                  ON
WHEN MATCHED THEN
WHEN NOT MATCHED BY TARGET THEN
WHEN NOT MATCHED BY SOURCE THEN ;

SQL MERGE Command Example

Imagine two tables we want to synchronize:

  • dbo.Job_Position (DESTINATION) – target table located in data warehouse/data mart
  • dbo.Job_Position_SourceSystem (SOURCE) table in source system from which we are going to synchronize data

Synchronized field will be the employee position – “Employee_Position”. MERGE syntax is very intuitive and it will contain three parts:

  • If the record exists both in source and target destination we execute UPDATE (WHEN MATCHED)
  • If the record does not exist in target table we execute INSERT (NOT MATCHED)
  • If the record does not exist in source table but exists in target table we execute DELETE (NOT MATCHED BY SOURCE)
MERGE dbo.Job_Position AS TARGET
USING  dbo.Job_Position_SourceSystem AS SOURCE
ON TARGET.ID_JobPosition = SOURCE.ID_JobPosition
WHEN MATCHED AND 1=1 THEN 
UPDATE SET TARGET.Employee_Position=SOURCE.Employee_Position
WHEN NOT MATCHED BY TARGET THEN
INSERT (ID_JobPosition, Employee_Position)
VALUES (ID_JobPosition, Employee_Position)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;

Note: In case you do not understand why I wrote AND 1=1 into „WHEN MATCHED“ section – my purpose was to hint that you can define conditions in MATCHED parts

Rate this post
Category: Handling SQL tables Tags:

About Jan Zedníček

My name is Jan Zedníček and I work as a freelancer. I have been working as a freelancer for many companies for more than 5 years. I used to work as a financial controller, analyst and manager at many different companies in field of banking and manufacturing. When I am not at work, I like playing volleyball, chess, doing a workout in the gym and I enjoy tasting of best quality rums. I am trying to summarize all my knowledge on this website not to forget them (because of the rum effect, you know =) and to put them forward to anyone. Don´t worry about asking for help or writing some comments.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.