📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your team uses MERGE for upserts in SQL Server. What are its known problems, why can concurrent MERGE statements still violate a primary key, what does HOLDLOCK change, and what safer upsert patterns would you use instead?

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.

Senior Theory Advanced concurrency locking merge sql-server t-sql upsert

🎯 Key points

  • MERGE is atomic (all its actions commit or roll back together) but not isolated from concurrent sessions under READ COMMITTED: the match check doesn't lock missing rows
  • Two sessions can both see 'not matched' and both insert, causing PK/unique violations (error 2627/2601) or duplicates without a constraint
  • Key-range locks only appear when you add WITH (HOLDLOCK) (= SERIALIZABLE on the target); they close the gap but increase blocking and deadlocks
  • Duplicate source keys raise error 8672 (row updated more than once); deduplicate the source with ROW_NUMBER before MERGE
  • History of bugs with filtered indexes, indexed views, triggers and foreign keys; test carefully
  • Safer pattern: UPDATE then INSERT inside a transaction with UPDLOCK, SERIALIZABLE, or INSERT ... WHERE NOT EXISTS plus unique constraint and retry
  • Always keep a unique constraint as the final guard, handle 2627/1205 explicitly and make the caller idempotent

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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."


The race

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)

Upsert options

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate understands concurrency in upserts and doesn't treat a single statement as isolated.

Green flags

  • Describes the NOT MATCHED race and the resulting PK violation
  • Explains HOLDLOCK as serializable with key-range locks
  • Knows MERGE's bug history and error 8672
  • Proposes UPDLOCK/SERIALIZABLE upsert, unique constraint and idempotent retries

Red flags

  • "MERGE is atomic so it's safe"
  • Uses NOLOCK or no constraint in an upsert
  • No plan for deadlocks

📚 Learn in depth

1. What MERGE does internally

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.

2. Why HOLDLOCK fixes it

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.

3. Known problems

  • Error 8672: the source contains two rows matching the same target row. Deduplicate the source first.
  • Historical bugs (many fixed, some "by design") involving filtered indexes, indexed views, triggers firing for all actions, and foreign keys. Aaron Bertrand's widely cited list is why many teams avoid MERGE for OLTP.
  • @@ROWCOUNT is the total of all actions; use OUTPUT $action to see which.
  • Must end with a semicolon.

4. The explicit upsert

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.

5. Idempotency and retries

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.

6. Batch loads

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.

Try it yourself

  1. Run a MERGE upsert in two SSMS windows with WAITFOR DELAY between the read and write (simulate with a transaction) and reproduce error 2627.
  2. Add WITH (HOLDLOCK) and watch the second session wait; inspect sys.dm_tran_locks for RangeS-U locks.
  3. Load-test both patterns with ostress or a small .NET program running 50 concurrent upserts.
  4. Feed MERGE a source with duplicate keys and see error 8672.

💻 Code

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);
            }
        }
    }
}

⚠ Common mistakes

  • Mistake: Assuming MERGE is atomic against other sessions. Why it is wrong: Atomicity means its actions commit or roll back together; it says nothing about isolation. Under READ COMMITTED the match check doesn't lock missing rows, so concurrent inserts race. Instead: Add HOLDLOCK or use the explicit UPDLOCK/SERIALIZABLE pattern.
  • Mistake: Using 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.
  • Mistake: Feeding MERGE a source with duplicate keys. Why it is wrong: Error 8672, or non-deterministic results. Instead: Deduplicate the source first, e.g. a CTE with ROW_NUMBER() OVER (PARTITION BY Sku ORDER BY ReceivedAt DESC) keeping rn = 1.
  • Mistake: Relying on locking alone with no unique constraint. Why it is wrong: Any other code path that inserts without the same hints creates duplicates. Instead: Keep a primary key or unique index as the final guard.
  • Mistake: Letting a unique-constraint violation on the INSERT branch bubble up as a 500. Why it is wrong: With the optimistic patterns (INSERT ... WHERE NOT EXISTS, or try-insert) a 2627/2601 is an expected outcome of a race, not a bug, and the update is lost. Instead: Catch 2627/2601 and retry the upsert (it will now take the UPDATE path), or translate it to a conflict response if the caller must decide.
  • Mistake: No retry for deadlocks. Why it is wrong: Serializable range locks make deadlocks more likely under load. Instead: Retry 1205 with backoff and make the operation idempotent.
  • Mistake: Using @@ROWCOUNT after MERGE to know whether a row was inserted. Why it is wrong: It counts all actions. Instead: Use OUTPUT $action.
  • Mistake: Using MERGE in tables with triggers or filtered indexes without testing. Why it is wrong: These have been the source of several MERGE bugs. Instead: Test edge cases or use separate statements.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about conditional updates for correctness under concurrency Why: Checks the related conditional UPDATE pattern for stock correctness.
    How to answer

    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.

  2. When: Candidate says HOLDLOCK makes MERGE safe Why: Checks understanding of how SERIALIZABLE prevents phantoms and why it increases blocking.
    How to answer

    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.

🛠 Real-world problems: how you handle them

PK violations from concurrent MERGE upserts during a sale
Situation
An [inventory sync] API received stock updates from [several warehouses] and upserted them into Azure SQL with MERGE, about [1,200] upserts per second at peak.
Signals
During a [sale] Application Insights logged hundreds of SqlException 2627 errors per hour on the upsert; some warehouses showed stale stock levels because the failed request wasn't retried.
Investigation
Correlated the failures by SKU and timestamp and found pairs of requests for the same SKU within milliseconds. Read the MERGE without HOLDLOCK and reproduced the race locally with two sessions and a delay. Checked the system_health session for deadlocks once HOLDLOCK was tested.
Resolution
Replaced MERGE with an UPDATE using UPDLOCK, SERIALIZABLE and an INSERT when no row was updated, in one transaction. Added a retry policy for 1205 and 2627 in the client, keeping the primary key as the final guard.
Prevention
Added a concurrency integration test that fires 50 parallel upserts for the same key, banned MERGE for OLTP in the team's SQL guidelines, and alerted on SqlException numbers in Application Insights.

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].

More in SQL Features

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me