Why can a SQL Server MERGE upsert fail with duplicate-key errors under concurrency, and what do HOLDLOCK and OUTPUT $action add?
answer
- two sessions, one missing key
- nothing to lock yet
- a synonym for SERIALIZABLE
- which action touched this row
- source columns in OUTPUT
basics
~20 sUnder default READ COMMITTED, two sessions can both find a new key missing and both insert it; one fails with Msg 2627 or 2601. WITH (HOLDLOCK) applies SERIALIZABLE to the target so the second waits, and OUTPUT $action names each row's action.
solid answer
~40 sA `MERGE` is one statement, but it is not atomic against other sessions: under lock-based `READ COMMITTED`, two sessions merging the same **new** key both see no matching row, both take the `WHEN NOT MATCHED` branch and both `INSERT`, so the second fails with Msg 2627 or 2601. Adding `WITH (HOLDLOCK)` to the target, a synonym for `SERIALIZABLE` on that table for the statement's transaction, keeps the range locks the read took, so the second session waits and then matches the row. The price is less concurrency and more blocking, which is why the documentation suggests separate `INSERT` and `UPDATE` statements under heavy concurrency. `OUTPUT $action` returns `INSERT`, `UPDATE` or `DELETE` for each affected row, and unlike `INSERT ... OUTPUT`, a `MERGE` can also output **source** columns.
code
sql · 14 linesDECLARE @changes TABLE (merge_action nvarchar(10), sku varchar(20));
MERGE dbo.inventory WITH (HOLDLOCK) AS t
USING (VALUES ('A-100', 5), ('B-200', 3)) AS s (sku, qty)
ON t.sku = s.sku
WHEN MATCHED THEN
UPDATE SET t.qty = t.qty + s.qty
WHEN NOT MATCHED BY TARGET THEN
INSERT (sku, qty) VALUES (s.sku, s.qty)
OUTPUT $action, s.sku INTO @changes (merge_action, sku);
SELECT merge_action, COUNT(*) AS row_count
FROM @changes
GROUP BY merge_action;go deeper
Recall MERGE's WHEN MATCHED and WHEN NOT MATCHED branches, the mandatory semicolon, and that OUTPUT can return INSERTED and DELETED values.
Explain what $action reports, how source columns in OUTPUT differ from INSERT's OUTPUT, and why Msg 8672 means a target row matched several source rows.
Walk through the duplicate-key race at READ COMMITTED, show how HOLDLOCK closes it, and name the blocking and deadlock cost you accept.
Decide where MERGE belongs: fine for batch synchronisation in quiet windows, while hot single-row upserts may be better as separate statements.
## T-SQL's MERGE in brief SQL Server's `MERGE target USING source ON condition` runs inserts, updates and deletes in one statement. Beyond the standard form, T-SQL adds rules and extensions you meet early: - the statement **must end with a semicolon**; without one it fails with Msg 10713; - **`WHEN NOT MATCHED BY SOURCE`** acts on target rows the source does not contain, which makes `MERGE` a full table synchroniser; - at most two `WHEN MATCHED` clauses (one `UPDATE`, one `DELETE`, the first with an extra `AND` condition), and only one `WHEN NOT MATCHED [BY TARGET]`; - a target row matched by two source rows fails with **Msg 8672**; - **`@@ROWCOUNT`** after a `MERGE` is the total of all inserted, updated and deleted rows. ## Why a concurrent upsert collides The race needs no exotic workload, only two requests that upsert the same new key at once, such as two stock updates for a SKU that does not exist yet: 1. Session A's `MERGE` reads the target for `sku = 'A-100'` and finds nothing. Under the default lock-based `READ COMMITTED`, there is no row to lock, and the shared locks the read took are not held to the end of the transaction. 2. Session B does the same and also finds nothing. 3. Both take `WHEN NOT MATCHED BY TARGET` and insert. 4. One insert wins; the other hits the unique index and fails with **Msg 2627** (a `PRIMARY KEY` or `UNIQUE` constraint) or **Msg 2601** (a unique index). Writing it as one statement does not change this: `MERGE` still performs its `INSERT`, `UPDATE` and `DELETE` operations, with its own locking, and the documentation warns that at scale it can bring complicated concurrency issues. ## What HOLDLOCK changes `MERGE dbo.inventory WITH (HOLDLOCK) AS t ...` applies **`HOLDLOCK`**, which is equivalent to **`SERIALIZABLE`**, to the target table only, for the duration of the transaction the statement runs in. Shared locks are held until the transaction ends and the read uses serializable semantics, so the range where the missing key would go stays locked. Session B now waits for A to commit, then finds the row and takes the `WHEN MATCHED` branch. The documentation states that in some scenarios where unique keys are both inserted and updated by the `MERGE`, `HOLDLOCK` prevents the unique key violations. The costs are real: - **less concurrency**: serializable range locks block other writers on that range until the transaction ends; - **more blocking and possible deadlocks** when many sessions merge overlapping ranges; - a well-chosen **unique index on the `ON` columns** matters, since it keeps the locked ranges narrow. When concurrency is high, the documentation suggests separate `UPDATE` and `INSERT` statements may block less than a `MERGE`. Whichever form you choose, the race exists until something holds a lock on the key range for the whole check-then-insert. ## OUTPUT with MERGE The **`OUTPUT`** clause returns a row for each target row affected, and with `MERGE` it gains two things: | Element | Meaning | |---|---| | `$action` | `nvarchar(10)` with `INSERT`, `UPDATE` or `DELETE` for that row | | `INSERTED.col` | the value after the change (`NULL` for a delete) | | `DELETED.col` | the value before the change (`NULL` for an insert) | | `source_alias.col` | a column of the **source** row that drove the action | The documentation calls `OUTPUT` the recommended way to query or count rows affected by a `MERGE`, for example grouping by `$action` to report how many rows were inserted and how many updated. The source-column access is a T-SQL idiom of its own. An `INSERT ... SELECT ... OUTPUT` can reference only `INSERTED` columns, because the `FROM`-table prefix in `OUTPUT` is available only to `DELETE`, `UPDATE` and `MERGE`. To copy rows and capture an **old-id to new-identity map**, developers write a `MERGE` whose `ON 1 = 0` never matches, so every source row is inserted, and output both `s.old_id` and `INSERTED.new_id`. ## OUTPUT rules that bite - `OUTPUT` without `INTO` is rejected with **Msg 334** if the target has an enabled trigger for that action. - An `OUTPUT INTO` table cannot have enabled triggers, take part in a `FOREIGN KEY` or carry `CHECK` constraints; a table variable or temporary table is the usual target. - Rows can reach the client even if the statement then fails and rolls back, so do not act on them after an error. - The order of `OUTPUT` rows is not guaranteed. Keep the `ON` clause to the matching columns only; the documentation warns that filtering the target there can return incorrect results.
- How do you capture old-to-new identity mappings when copying rows in SQL Server?Use `MERGE dbo.target AS t USING dbo.source AS s ON 1 = 0 WHEN NOT MATCHED THEN INSERT (...) VALUES (...) OUTPUT s.old_id, INSERTED.new_id INTO @map;`. Because `ON 1 = 0` never matches, every source row is inserted, and `MERGE`'s `OUTPUT` may reference source columns, which an `INSERT ... SELECT` with `OUTPUT` cannot.
- Why does an UPDATE ... OUTPUT INSERTED.* fail on a table that has an AFTER UPDATE trigger?`OUTPUT` without `INTO` is not allowed when the target has an enabled trigger for that action, and SQL Server raises Msg 334. Send the rows to a table variable or temporary table with `OUTPUT ... INTO`, then select from it, or rethink the trigger.
- MERGE is a single statement, so concurrent upserts cannot collide.
- HOLDLOCK on the target has no cost beyond the one MERGE statement.
- Msg 8672 means two sessions inserted the same key at once.
- $action returns the name of the WHEN clause that fired.
- An INSERT ... SELECT can output source columns just like MERGE.
- OUTPUT rows are safe to use even when the statement fails.