Microsoft Docs SQL

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
     ]
[ ; ]
ParameterDescription
target_tableThe table that is the target of the merge operation.
source_tableThe source of rows to be merged. Can be a table, view, derived table, or CTE.
merge_search_conditionPredicate that defines how rows from source match rows in target.
matched_actionUPDATE, DELETE, or DO NOTHING when a source row matches a target row.
not_matched_by_target_actionINSERT when a source row does not match any target row.
not_matched_by_source_actionDELETE (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