MERGE is a new feature that provides an efficient way to perform multiple DML operations. In previous versions of SQL Server, we had to write separate statements to INSERT, UPDATE, or DELETE data based on certain conditions, but now, using MERGE statement we can include the logic of such data modifications in one statement that even checks when the data is matched then just update it and when unmatched then insert it.
One of the most important advantage of MERGE statement is all the data is read and processed only once. In previous versions three different statement has to be written to process three different activity (INSERT, UPDATE or DELETE), however using MERGE statement all update activity can be done in one pass of database table. This is quite an improvement in performance of database query.
Syntax of MERGE statement is as following:
MERGE
[ TOP ( expression ) [ PERCENT ] ]
[ INTO ] target_table [ WITH ( <merge_hint> ) ] [ [ AS ] table_alias]
USING <table_source>
ON <merge_search_condition>
[ WHEN MATCHED [ AND <clause_search_condition> ]
THEN <merge_matched> ]
[ WHEN NOT MATCHED [ BY TARGET ] [ AND <clause_search_condition> ]
THEN <merge_not_matched> ]
[ WHEN NOT MATCHED BY SOURCE [ AND <clause_search_condition> ]
THEN <merge_matched> ]
[ <output_clause> ]
[ OPTION ( <query_hint> [ ,...n ] ) ]
;
Example:
Let’s create Student Details and StudentTotalMarks and inserted some records.
Student Details:
USE AdventureWorks
GO
CREATE TABLE StudentDetails
(
StudentID INTEGER PRIMARY KEY,
StudentName VARCHAR(15)
)
GO
INSERT INTO StudentDetails
VALUES(1,'SMITH')
INSERT INTO StudentDetails
VALUES(2,'ALLEN')
INSERT INTO StudentDetails
VALUES(3,'JONES')
INSERT INTO StudentDetails
VALUES(4,'MARTIN')
INSERT INTO StudentDetails
VALUES(5,'JAMES')
GO
StudentTotalMarks:
CREATE TABLE StudentTotalMarks
(
StudentID INTEGER REFERENCES StudentDetails,
StudentMarks INTEGER
)
GO
INSERT INTO StudentTotalMarks
VALUES(1,230)
INSERT INTO StudentTotalMarks
VALUES(2,255)
INSERT INTO StudentTotalMarks
VALUES(3,200)
GO

In our example we will consider three main conditions while we merge this two tables.
- Delete the records whose marks are more than 250.
- Update marks and add 25 to each as internals if records exist.
- Insert the records if record does not exists.
Now we will write MERGE process for tables created earlier. We will make sure that we will have our three conditions discussed above are satisfied.
MERGE StudentTotalMarks AS stm
USING (SELECT StudentID,StudentName FROM StudentDetails) AS sd
ON stm.StudentID = sd.StudentID
WHEN MATCHED AND stm.StudentMarks > 250 THEN DELETE
WHEN MATCHED THEN UPDATE SET stm.StudentMarks = stm.StudentMarks + 25
WHEN NOT MATCHED THEN
INSERT(StudentID,StudentMarks)
VALUES(sd.StudentID,25);
GO
There are two very important points to remember while using MERGE statement.
- Semicolon is mandatory after the merge statement.
- When there is a MATCH clause used along with some condition, it has to be specified first amongst all other WHEN MATCH clause.
After the MERGE statement has been executed, we should compare previous resultset and new resultset to verify if our three conditions are carried out.

AS we can see there are 5 rows updated. StudentID 2 is deleted as it is more than 250, 25 marks have been added to all records that exists i.e StudentID 1,3 and the records that did not exists i.e. 4 and 5 are now inserted in StudentTotalMarks .
MERGE statement is very handy improvement for T-SQL developers who have to update database tables with complicated logic. MERGE statement also improves the performance of database as it passes through data only once.
Reference : Pinal Dave (http://blog.SQLAuthority.com)




Nice article…I have one doubt…
Do we need to select StudentName in the Source Table like
“SELECT StudentID,StudentName FROM StudentDetails”, which is never used in the Join?
can we transfer different combo box value into different tables at the database by using one one sql insert query
What if we want a conditional merge or insert
Eg: if(condition = true)
(
insert into table1 values(select * from tableE) where ..
)
else
(
)
how does such things work, can u help me.
Thanks
Nice Article & Nice Feature of SQL Server 2008
Thanx
Thanks
Hi Pinal Dave,
Thanks for most of the very useful articles you write..Just something that still puzzles me and you might have the answer.
To be it seems 2008 MERGE statement and CDC perform the same function during the ETL process that is best used in SCD situations.
What i do see is CDC tracking and capturing data into a Different Table..
My question is do they perform different functions.
Thanks
[...] What is MERGE Statement? MERGE is a new feature that provides an efficient way to perform multiple DML operations. In previous versions of SQL Server, we had to write separate statements to INSERT, UPDATE, or DELETE data based on certain conditions, but now, using MERGE statement we can include the logic of such data modifications in one statement that even checks when the data is matched then just update it and when unmatched then insert it. One of the most important advantages of MERGE statement is all the data is read and processed only once. (Read More Here) [...]
How to merge 2 tables … eg : Table1 and Table2 , these two tables should be merged into Table3 .. means creating this new table3 contaning the data of table1 and table2
@dinesh.
Use full outer join for tables 1 and table 2. You should have at least one column common in between these two tables.
Sample Script
Select A.cola, A.Colb, A.colc, B.colb, B.colc
FROM Table1 A Full Outer Join Table2 B on A.cola = B.cola
Refer to this article for more details on Joins,
http://blog.sqlauthority.com/2009/04/13/sql-server-introduction-to-joins-basic-of-joins/
~ IM.
thenqq Imran :)
one more doubt ,is it possbile to combine the 2 tables into a new table .. The join keyword is only selecting the information.
Can you cancel or stop a MERGE statement ? What if I need to Merge 2 Huge tables and then for some reason, I would like to cancel the curent operation. Is this possible ? Can I Rollback ? Thanks
Hi Pinal Dave,
really great information!!
please tell me how to merge data into two table
like newtable has data for table1 and table2
table1 and table2 has matching columns
so how i’ll fetch table1’s new indent value to insert record for it into table2
–
thanks in advance