Merge Statement to perform insert , update and delete in one statement

This example, demonstrate how to perform insert, update and delete on single statement using MERGE. If you are a Database Developer/BI expert, you would need to refresh the target table to match the source tables periodically. Prior to SQL Server 2008, you would need to perform this task by writing separate T-SQL logic for insert, delete and update. Starting from SQL Server 2008, you can perform all three SQL Statements (Insert, Update and Delete) in one statement using MERGE Statement.

What is the use of MERGE statement in SQL Server?

Merge statement introduced in SQL Server 2008 allows us to perform inserts, updates and deletes in one statement, which means we no longer have to use multiple statements to perform insert, update and delete.

Basic Merge syntax:

Merge_Statement

To try the example , you’ll need to first run the following script to create and populate the tables used in the examples:

 -- CREATE A SOURCE TABLE
CREATE TABLE [DBO].[STUDENT_SOURCE](
[ID] [INT] NOT NULL,
[STUDENTNAME] [NCHAR](50) NOT NULL,
CONSTRAINT [PK_STUDENT_SOURCE] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] 
 -- CREATE A TARGET TABLE</pre>
CREATE TABLE [DBO].[STUDENT_TARGET](
[ID] [INT] NOT NULL,
[STUDENTNAME] [NCHAR](50) NOT NULL,
CONSTRAINT [PK_STUDENT_TARGET] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] 
 --- INSERT RECORDS INTO SOURCE TABLE
INSERT INTO [STUDENT_SOURCE] VALUES (1,'RAMA')
INSERT INTO [STUDENT_SOURCE] VALUES (2,'SANKAR')
--- INSERT RECORDS INTO TARGET TABLE
INSERT INTO [STUDENT_TARGET] VALUES (1, 'RAMASANKAR')
INSERT INTO [STUDENT_TARGET] VALUES (3, 'MURTHY') 

After you ran the above script, you have two tables(STUDENT_SOURCE and STUDENT_TARGET)  created with some sample data as below.

Tables

Now, I will use MERGE statement to synchronize target table with source.

 MERGE [STUDENT_TARGET] AS T
USING [STUDENT_SOURCE] AS S
ON T.ID = S.ID
WHEN MATCHED THEN
UPDATE SET T.STUDENTNAME = S.STUDENTNAME
WHEN NOT MATCHED BY TARGET THEN
INSERT (ID, STUDENTNAME) VALUES (S.ID,S.STUDENTNAME)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
(3 row(s) affected) 

There you go, Three rows are modified which means one update, one Insert  and one Delete performed in single statement.

After executing the Merge statement we can see that both source and target are identical.

 SELECT * FROM STUDENT_SOURCE;</pre>
SELECT * FROM STUDENT_TARGET; 

After_Table

MERGE statement is very useful improvement to update database tables with complex logic. Better Performance and scalability can be achieved with MERGE statement.

Hope you enjoyed the post!

Cheers

Ramasankar Molleti

LinkedIn: LinkedIn Profile

Twitter: Twitter

Published by Ramasankar

As a Principal Cloud Architect with over 18 years of experience, I am dedicated to revolutionizing IT landscapes through cutting-edge cloud solutions. My expertise spans Cloud Architecture, Security Architecture, Solution Design, Cloud Migration, Database Transformation, Development, and Big Data Analytics.Currently, I spearhead cloud initiatives with a focus on Infrastructure, Containerization, Security, Big Data, Machine Learning, and Artificial Intelligence. I collaborate closely with development teams to architect, build, and manage robust cloud ecosystems that drive business growth and technological advancement.Core Competencies: • Cloud Platforms: AWS, Google Cloud Platform, Microsoft Azure • Technologies: Kubernetes, Serverless Computing, Microservices • Databases: MS SQL Server, PostgreSQL, Oracle, MongoDB, Amazon Redshift, DynamoDB, Aurora • Industries: Finance, Retail, Manufacturing. Throughout my career, I’ve had the privilege of working with industry leaders such as OCC, Gate Gourmet, Walgreens, and Johnson Controls, gaining invaluable insights across diverse sectors.As a lifelong learner and knowledge sharer, I take pride in being the first in my organization to complete all major AWS certifications. I am passionate about mentoring and guiding fellow professionals in their cloud journey, fostering a culture of continuous learning and innovation.Let’s connect and explore how we can leverage cloud technologies to transform your business: • LinkedIn: https://www.linkedin.com/in/ramasankar-molleti-23b13218/ • Book a mentorship session: [1:1] Together, let’s architect the future of cloud computing and drive technological excellence. Disclaimer The views expressed on this website/blog are mine alone and do not reflect the views of my company. All postings on this blog are provided “AS IS” with no warranties, and confers no rights. The owner of https://ramasankarmolleti.com will not be liable for any errors or omissions in this information nor for the availability of this information. The owner will not be liable for any losses, injuries, or damages from the display or use of this information.

Leave a comment