MERGE (Transact‑SQL)
The MERGE statement enables you to perform insert, update, or delete operations on a target table based on the results of a join with a source table. It is often referred to as an “upsert” operation.
Syntax
Arguments
Examples
MERGE [TOP (expression) [ PERCENT ] ] [ INTO ] target_table [ WITH ([ ,...n ] ) ] USING source_table ON [ WHEN MATCHED [ AND ] THEN ] [ WHEN NOT MATCHED BY TARGET [ AND ] THEN ] [ WHEN NOT MATCHED BY SOURCE [ AND ] THEN ] [ ; ]
| Parameter | Description |
|---|---|
target_table | The table that is the target of the merge operation. |
source_table | The source of rows to be merged. Can be a table, view, derived table, or CTE. |
merge_search_condition | Predicate that defines how rows from source match rows in target. |
matched_action | UPDATE, DELETE, or DO NOTHING when a source row matches a target row. |
not_matched_by_target_action | INSERT when a source row does not match any target row. |
not_matched_by_source_action | DELETE (or UPDATE) when a target row has no matching source row. |
Example – Upsert Employees
-- Target table
CREATE TABLE dbo.Employee (
EmployeeID INT PRIMARY KEY,
Name NVARCHAR(100),
Salary MONEY
);
-- Source data (could be a staging table)
DECLARE @NewData TABLE (
EmployeeID INT,
Name NVARCHAR(100),
Salary MONEY
);
INSERT INTO @NewData VALUES
(1, N'Alice', 75000),
(2, N'Bob', 62000),
(4, N'Diana', 85000); -- New employee
MERGE dbo.Employee AS T
USING @NewData AS S
ON T.EmployeeID = S.EmployeeID
WHEN MATCHED THEN
UPDATE SET T.Name = S.Name,
T.Salary = S.Salary
WHEN NOT MATCHED BY TARGET THEN
INSERT (EmployeeID, Name, Salary)
VALUES (S.EmployeeID, S.Name, S.Salary)
WHEN NOT MATCHED BY SOURCE THEN
DELETE; -- Remove employees not present in source
Note: Use the
OUTPUT clause with MERGE to capture inserted, updated, or deleted rows for auditing.Best Practices
- Always include a
WHEN NOT MATCHED BY SOURCEclause if you need to handle orphaned rows. - Consider using explicit
INSERT ... OUTPUTorUPDATE ... OUTPUTfor audit trails instead of relying solely on MERGE. - Beware of concurrency issues; MERGE is atomic but may be affected by trigger side effects.