- Aggregate functions
- AVERAGE function
- BETWEEN operator
- CASE expression
- CAST() function
- COALESCE() function
- Comment
- Common table expression
- Constraints
- CONVERT function
- Cursor
- Data types
- Date functions
- DELETE statement
- DROP TABLE statement
- EXISTS operator
- HAVING clause
- IF statement
- Index
- IS NOT NULL condition
- IS NULL condition
- Joins
- LAG function
- LENGTH() function
- LIKE operator
- MERGE statement
- Normalization
- Not equal
- Operators
- ORDER BY clause
- Partition
- Pivot table
- Regex
- REPLACE function
- ROUND function
- SELECT DISTINCT clause
- SELECT statement
- Set operators
- Stored procedure
- String functions
- Subquery
- Substring
- Temporary table
- Transaction
- Trigger
- TRUNCATE TABLE
- UPDATE statement
- Views
- WHERE clause
- Window functions
SQL
SQL MERGE Statement: Syntax, Usage, and Examples
The SQL MERGE statement lets you perform INSERT
, UPDATE
, and DELETE
operations in a single command. It’s useful for synchronizing tables by comparing a source with a target and applying the appropriate changes.
How to Use the SQL MERGE Statement
Use the SQL MERGE statement when you want to compare two tables—typically a source and a target—and update, insert, or delete rows based on the results of that comparison. Here’s a basic example of the syntax:
MERGE INTO TargetTable AS target
USING SourceTable AS source
ON target.ID = source.ID
WHEN MATCHED THEN
UPDATE SET target.Name = source.Name
WHEN NOT MATCHED THEN
INSERT (ID, Name) VALUES (source.ID, source.Name);
Use this to update existing records and insert new ones depending on whether a match exists between the target and source tables.
You can also include a WHEN NOT MATCHED BY SOURCE
clause to delete rows that exist in the target but not in the source:
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
This optional clause allows you to fully align the target table with the source.
When to Use the SQL MERGE Statement
Use the SQL MERGE statement when your goal is to merge data between two tables without writing multiple queries. It simplifies what would otherwise be a three-step process.
Sync Two Tables
When you're managing staging tables or syncing data between systems, use the MERGE statement in SQL to apply differences quickly and consistently.
Upsert Data
Use MERGE to perform an "upsert"—an update if the record exists, or an insert if it doesn’t. This pattern is common when loading data from external sources like APIs or flat files.
Clean Up Outdated Data
With the WHEN NOT MATCHED BY SOURCE
clause, use the SQL MERGE statement to remove records from the target that no longer exist in the source. This is useful when keeping your main table lean and up to date.
Examples of the SQL MERGE Statement
Let’s look at common use cases for the MERGE statement SQL syntax in action.
Example 1: Synchronizing Customer Data
MERGE INTO Customers AS target
USING NewCustomers AS source
ON target.CustomerID = source.CustomerID
WHEN MATCHED THEN
UPDATE SET target.Name = source.Name, target.Email = source.Email
WHEN NOT MATCHED THEN
INSERT (CustomerID, Name, Email)
VALUES (source.CustomerID, source.Name, source.Email);
Use this to update existing customer records or insert new ones.
Example 2: Handling Deletions
MERGE INTO Employees AS target
USING CurrentEmployees AS source
ON target.EmployeeID = source.EmployeeID
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
Use this to remove records from the Employees table that no longer appear in the updated list.
Example 3: MERGE With All Three Actions
MERGE INTO Inventory AS target
USING StockUpdate AS source
ON target.ProductID = source.ProductID
WHEN MATCHED THEN
UPDATE SET target.Quantity = source.Quantity
WHEN NOT MATCHED THEN
INSERT (ProductID, Quantity)
VALUES (source.ProductID, source.Quantity)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
Use this pattern when you need a full merge: updating existing rows, adding new products, and removing discontinued ones.
Learn More About the MERGE Statement in SQL
MERGE Statement in SQL Server
The SQL MERGE statement is supported in SQL Server. Here’s a SQL Server MERGE statement example that incorporates OUTPUT:
MERGE INTO SalesTargets AS target
USING ActualSales AS source
ON target.EmployeeID = source.EmployeeID
WHEN MATCHED THEN
UPDATE SET target.Goal = source.TotalSales
WHEN NOT MATCHED THEN
INSERT (EmployeeID, Goal)
VALUES (source.EmployeeID, source.TotalSales)
OUTPUT $action, inserted.*, deleted.*;
Use OUTPUT in SQL Server to track what rows were updated, inserted, or deleted during the operation.
MERGE vs. Individual Statements
You could use separate UPDATE
, INSERT
, and DELETE
queries, but you’d have to manage the logic manually and run each command in sequence. That increases complexity and may lead to inconsistencies in high-concurrency environments.
Using the SQL MERGE statement ensures that these actions are treated as a single atomic operation.
SQL Server MERGE Statement Example With Variables
You can merge values using parameters or variables in stored procedures:
DECLARE @ProductID INT = 42;
DECLARE @Quantity INT = 100;
MERGE INTO Inventory AS target
USING (SELECT @ProductID AS ProductID, @Quantity AS Quantity) AS source
ON target.ProductID = source.ProductID
WHEN MATCHED THEN
UPDATE SET target.Quantity = source.Quantity
WHEN NOT MATCHED THEN
INSERT (ProductID, Quantity)
VALUES (source.ProductID, source.Quantity);
Use variables to dynamically update or insert values into your target table.
Considerations When Using MERGE
Although the SQL MERGE statement simplifies logic, it has some caveats:
- It's more complex than simple DML statements. Start with SELECTs before running it to verify results.
- Some databases (like MySQL) don’t support MERGE, so you'll need to simulate it with
INSERT ... ON DUPLICATE KEY UPDATE
or other mechanisms. - Be aware of race conditions in concurrent environments. MERGE is atomic, but in systems with high writes, deadlocks can occur.
- SQL Server's MERGE implementation has had bugs in certain versions, so test thoroughly before using it in production systems.
Alternatives for Unsupported Systems
If your system doesn’t support MERGE, simulate the behavior using a transaction:
BEGIN TRANSACTION;
UPDATE Products
SET Price = 29.99
WHERE ProductID = 101;
IF @@ROWCOUNT = 0
BEGIN
INSERT INTO Products (ProductID, Price)
VALUES (101, 29.99);
END
COMMIT;
Use this structure when you need MERGE-like logic in platforms without native support.
Use the SQL MERGE statement when you need precise, conditional synchronization between two datasets. It reduces boilerplate, improves performance, and gives you more control over how your data evolves. Whether you're working on data warehousing, APIs, or real-time applications, mastering this statement will streamline how you manage data consistency.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.