The T-SQL MERGE statement: syntax, its history of bugs, the race condition under concurrency, HOLDLOCK and serializable range locks, duplicate source rows, and safer upsert patterns.
MERGE looks atomic, but under READ COMMITTED the "does the row exist?" check and the insert are separate steps, so two sessions can both see NOT MATCHED and both insert, giving PK violations (error 2627) or duplicates if there's no constraint. Adding WITH (HOLDLOCK) (serializable on the target) takes key-range locks that close that gap, at the cost of more blocking and deadlock risk. MERGE also has a long history of bugs with filtered indexes, indexed views and triggers, and fails with error 8672 when the source has duplicate keys.
For single-row upserts I prefer UPDATE ... WITH (UPDLOCK, SERIALIZABLE) then INSERT if no rows, in one transaction, with a unique constraint as the final guard.
"MERGE is convenient: one statement that inserts, updates and deletes based on a join between a source and a target. The problem is concurrency. Under the default READ COMMITTED level, SQL Server reads the target to decide matched or not matched, and only takes exclusive locks when it writes. Two sessions upserting the same key at the same moment can both find no row, both go down the NOT MATCHED branch, and the second one fails with a primary key violation. If there isn't a unique constraint, you silently get duplicates. People assume a single statement is atomic in that sense; it's atomic for rollback, not isolated from other sessions.
The fix inside MERGE is WITH (HOLDLOCK) on the target, which is SERIALIZABLE for that table. The lookup then takes a key-range lock on the gap where the row would go, so the second session waits. That works, but it increases blocking, and range locks are a common source of deadlocks under load. On top of that, MERGE has had a long list of bugs over the years with filtered indexes, indexed views, triggers and foreign keys, which is why many DBAs ban it for OLTP. It also errors with 8672 if the source has the same key twice.
For example, at [company] we had [an inventory sync] using MERGE from an API. Under [Black Friday] load we started seeing PK violations from concurrent requests for the same SKU. I [replaced it with an UPDATE using UPDLOCK and SERIALIZABLE hints, then an INSERT when @@ROWCOUNT was zero, in one transaction, kept the unique constraint and made the caller retry on 2627 or 1205]. Errors dropped to [zero].
I still use MERGE for batch loads into staging or a warehouse where only one process writes. For OLTP upserts, the explicit pattern is easier to reason about and test."
| Time | Session A | Session B |
|---|---|---|
| t1 | MERGE reads target: key 42 not found | |
| t2 | MERGE reads target: key 42 not found | |
| t3 | INSERT 42, commits | |
| t4 | INSERT 42: error 2627 (or a duplicate if no constraint) |
| Pattern | Safe under concurrency | Notes |
|---|---|---|
| MERGE (no hint) | No | Race on NOT MATCHED |
| MERGE WITH (HOLDLOCK) | Yes | Range locks, more blocking; still has MERGE edge cases |
| UPDATE (UPDLOCK, SERIALIZABLE) then INSERT | Yes | Clear, single-row OLTP default |
| INSERT ... WHERE NOT EXISTS + unique constraint + retry | Yes with retry | Optimistic; good when inserts dominate |
| Try INSERT, catch 2627, then UPDATE | Yes | Good when the row usually doesn't exist; exceptions cost |
An inventory sync processed about 1,200 upserts per second at peak and logged 300 to 500 PK violations per hour from MERGE. After switching to the UPDATE-then-INSERT pattern with UPDLOCK, SERIALIZABLE and a retry on deadlock, violations went to zero and p95 latency stayed under 8 ms.
Checks that the candidate understands concurrency in upserts and doesn't treat a single statement as isolated.
Green flags
Red flags
MERGE target USING source ON key
|
Join source to target (read, shared/update locks per isolation level)
|
For each row: classify MATCHED / NOT MATCHED BY TARGET / NOT MATCHED BY SOURCE
|
Clustered Index Merge operator applies INSERT / UPDATE / DELETE
Under READ COMMITTED, shared locks on rows read are released as soon as each row is read, and a missing row has no lock at all. That gap is the race.
HOLDLOCK = SERIALIZABLE for that table. When the seek finds no key 42, SQL Server takes a RangeS-U (or RangeS-S) lock on the range between neighbouring keys. Another session trying the same lookup waits. After the first commits, the second sees the row and takes the MATCHED branch. This requires an index on the join key; without it, range locks cover much more and blocking explodes.
@@ROWCOUNT is the total of all actions; use OUTPUT $action to see which.BEGIN TRAN
UPDATE ... WITH (UPDLOCK, SERIALIZABLE) WHERE Key = @k -- locks row or range
IF @@ROWCOUNT = 0 INSERT ... -- nobody can insert in between
COMMIT
UPDLOCK means two sessions don't both take shared range locks and then deadlock trying to convert them.
Even with correct locking, deadlocks (1205) can happen under load. The caller should retry with backoff, and the operation must be idempotent (same input, same end state). Keep the unique constraint as the last line of defence.
For staging-to-target loads run by one process, MERGE is fine and concise. Use OUTPUT $action, inserted.*, deleted.* for auditing, and consider separate UPDATE and INSERT statements if MERGE plans misbehave.
WAITFOR DELAY between the read and write (simulate with a transaction) and reproduce error 2627.WITH (HOLDLOCK) and watch the second session wait; inspect sys.dm_tran_locks for RangeS-U locks.ostress or a small .NET program running 50 concurrent upserts.MERGE with HOLDLOCK, and the explicit upsert I use for OLTP.
CREATE TABLE dbo.Inventory (
Sku varchar(32) NOT NULL CONSTRAINT PK_Inventory PRIMARY KEY,
OnHand int NOT NULL,
UpdatedAt datetime2(3) NOT NULL
);
GO
-- MERGE: safe only with HOLDLOCK on the target
CREATE OR ALTER PROCEDURE dbo.UpsertInventory_Merge @Sku varchar(32), @OnHand int
AS
BEGIN
SET NOCOUNT, XACT_ABORT ON;
MERGE dbo.Inventory WITH (HOLDLOCK) AS t
USING (VALUES (@Sku, @OnHand)) AS s (Sku, OnHand)
ON t.Sku = s.Sku
WHEN MATCHED THEN
UPDATE SET t.OnHand = s.OnHand, t.UpdatedAt = SYSUTCDATETIME()
WHEN NOT MATCHED BY TARGET THEN
INSERT (Sku, OnHand, UpdatedAt) VALUES (s.Sku, s.OnHand, SYSUTCDATETIME());
END;
GO
-- Preferred for single-row OLTP upserts
CREATE OR ALTER PROCEDURE dbo.UpsertInventory @Sku varchar(32), @OnHand int
AS
BEGIN
SET NOCOUNT, XACT_ABORT ON;
BEGIN TRANSACTION;
UPDATE dbo.Inventory WITH (UPDLOCK, SERIALIZABLE) -- lock the row, or the gap if missing
SET OnHand = @OnHand, UpdatedAt = SYSUTCDATETIME()
WHERE Sku = @Sku;
IF @@ROWCOUNT = 0
INSERT dbo.Inventory (Sku, OnHand, UpdatedAt)
VALUES (@Sku, @OnHand, SYSUTCDATETIME());
COMMIT;
END;
GO
using System.Data;
using Microsoft.Data.SqlClient;
namespace Inventory.Infrastructure;
public sealed class InventoryWriter(string connectionString)
{
// Deadlock victim (1205) or a rare PK race (2627) are retried; the upsert is idempotent.
public async Task UpsertAsync(string sku, int onHand, CancellationToken ct)
{
for (var attempt = 1; ; attempt++)
{
try
{
await using var conn = new SqlConnection(connectionString);
await conn.OpenAsync(ct);
await using var cmd = new SqlCommand("dbo.UpsertInventory", conn) { CommandType = CommandType.StoredProcedure };
cmd.Parameters.Add("@Sku", SqlDbType.VarChar, 32).Value = sku; // varchar, not nvarchar
cmd.Parameters.Add("@OnHand", SqlDbType.Int).Value = onHand;
await cmd.ExecuteNonQueryAsync(ct);
return;
}
catch (SqlException ex) when ((ex.Number is 1205 or 2627) && attempt < 3)
{
await Task.Delay(TimeSpan.FromMilliseconds(50 * attempt), ct);
}
}
}
}
HOLDLOCK or use the explicit UPDLOCK/SERIALIZABLE pattern.HOLDLOCK without an index on the join key. Why it is wrong: Range locks cover large parts of the table, causing heavy blocking. Instead: Ensure the ON clause seeks on a unique index.ROW_NUMBER() OVER (PARTITION BY Sku ORDER BY ReceivedAt DESC) keeping rn = 1.@@ROWCOUNT after MERGE to know whether a row was inserted. Why it is wrong: It counts all actions. Instead: Use OUTPUT $action.The senior answer separates atomicity from isolation. A single statement rolls back as a unit, but it doesn't stop another session reading the same gap. Whatever pattern you use, think about what happens when two requests for the same key arrive in the same millisecond, keep a unique constraint, and make the caller idempotent with retries.
| Option | Fits when | Cost | Not when |
|---|---|---|---|
| MERGE with HOLDLOCK | Batch loads, single writer, multi-action syncs | MERGE edge cases, range locks | High-concurrency OLTP |
| UPDATE then INSERT (UPDLOCK, SERIALIZABLE) | Single-row OLTP upserts | Range locks on misses | Huge batch syncs |
| INSERT, catch 2627, UPDATE | Inserts usually new | Exception handling cost | Mostly updates |
| EF Core: check then add | Low concurrency | Race without constraint | Hot keys |
Measure with load tests at realistic concurrency, sys.dm_tran_locks to see range locks, and deadlock graphs from the system_health session.
The code shows the classic problems: throw ex destroys the stack trace; catching Exception and returning null swallows real failures; logging ex.Message loses the chain; catch-log-rethrow at every layer duplicates logs; .Result blocks and wraps errors in AggregateException; async void crashes the process; throwing Exception gives callers nothing to catch; clean-up outside finally leaks the lock; exceptions used for control flow (parse in try/catch); and cancellation logged as an error. The rewrite uses async Task all the way, using/finally for clean-up, Try methods for expected failures, a specific domain exception with an inner exception, filters for transient retries, and one global handler that logs once.
Key-range locks protect the gap between index keys so no other session can insert a row that would change the result of a range read. They appear only under SERIALIZABLE (or the HOLDLOCK hint). Modes such as RangeS-S, RangeS-U and RangeI-N combine a range part and a key part. They prevent phantoms and make upserts safe, but they need a suitable index (otherwise far more is locked), increase blocking, and are a common cause of deadlocks.
How to tell it (STAR)
**S:** At [company], our inventory upserts started failing with primary key violations during a [sale]. **T:** I needed to stop the errors and make sure no stock update was lost. **A:** I traced pairs of requests for the same SKU arriving together and showed MERGE's NOT MATCHED branch races under READ COMMITTED. I replaced it with an UPDLOCK, SERIALIZABLE update-then-insert, kept the primary key, and added idempotent retries plus a parallel test. **R:** Violations went from about [400 an hour] to [zero] and p95 stayed under [8 ms].
Last updated 23 Nov 2026.