Guides

Violation of PRIMARY KEY constraint (Msg 2627): find the duplicate and fix the upsert race

By Scott Coffey, Senior Database Developer. Updated 2026-12-01.

An insert that works almost every time fails with this:

Msg 2627, Level 14, State 1, Procedure dbo.Customer_Upsert_Naive, Line 10
Violation of PRIMARY KEY constraint 'PK_Customer'. Cannot insert duplicate key in object 'dbo.Customer'. The duplicate key value is (42).
The statement has been terminated.

SQL Server refused a row because a row with the same key already exists. Nothing was written by that statement. The hard part is working out why the key was already there, because there are only a few common causes and each one has a different fix.

Step 1: read what the error tells you

Msg 2627 means a PRIMARY KEY or UNIQUE constraint was violated. Msg 2601 is the same problem on a unique index that was created with CREATE UNIQUE INDEX rather than as a constraint:

Msg 2601, Level 14, State 1, Line 1
Cannot insert duplicate key row in object 'dbo.Customer' with unique index 'UX_Customer_Email'. The duplicate key value is ([email protected]).
The statement has been terminated.

Both messages name the object, the constraint or index, and the duplicate value. Copy all three. "The statement has been terminated" means only that statement was rolled back. Unless XACT_ABORT is on or the code catches the error and rolls back, earlier statements in the same transaction are still pending.

Step 2: find the constraint and its key columns

The value in the message is listed in key column order. Confirm which columns those are, and whether the index has a filter:

SELECT i.name AS index_name,
       i.is_primary_key, i.is_unique_constraint, i.is_unique,
       c.name AS key_column, ic.key_ordinal,
       i.filter_definition
FROM sys.indexes AS i
JOIN sys.index_columns AS ic
  ON ic.object_id = i.object_id AND ic.index_id = i.index_id
JOIN sys.columns AS c
  ON c.object_id = ic.object_id AND c.column_id = ic.column_id
WHERE i.object_id = OBJECT_ID(N'dbo.Customer')
  AND i.name = N'PK_Customer'
  AND ic.key_ordinal > 0
ORDER BY ic.key_ordinal;

Filter on the table as well as the name, because index names only have to be unique within a table. Then look at the existing row with that key. Its timestamps or audit columns often show whether it arrived seconds earlier from another session or months earlier from a load.

Step 3: check the batch for duplicate keys

For INSERT ... SELECT from a staging table, the duplicate is often inside the batch itself, so the insert fails even when the target table is empty. Check both directions before loading:

-- keys that appear more than once in the batch
SELECT CustomerId, COUNT(*) AS copies
FROM dbo.CustomerStaging
GROUP BY CustomerId
HAVING COUNT(*) > 1;

-- keys that already exist in the target
SELECT s.CustomerId
FROM dbo.CustomerStaging AS s
WHERE EXISTS (SELECT 1 FROM dbo.Customer AS c WHERE c.CustomerId = s.CustomerId);

If the duplicates are expected, decide which copy wins and write that rule down in the load, for example the most recent row per key:

WITH ranked AS (
    SELECT CustomerId, Email, DisplayName,
           ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY LoadedAt DESC) AS rn
    FROM dbo.CustomerStaging
)
INSERT dbo.Customer (CustomerId, Email, DisplayName)
SELECT r.CustomerId, r.Email, r.DisplayName
FROM ranked AS r
WHERE r.rn = 1
  AND NOT EXISTS (SELECT 1 FROM dbo.Customer AS c WHERE c.CustomerId = r.CustomerId);

Rows that already exist should go through an update, not be dropped silently. Avoid IGNORE_DUP_KEY = ON as a fix: it turns the error into a warning and discards rows without telling the caller which ones.

Step 4: check the identity seed

If the key is an identity column and nobody supplies values, a duplicate usually means the seed was moved below existing values, for example by a DBCC CHECKIDENT ... RESEED after a partial cleanup, or by data copied in with IDENTITY_INSERT from another table. Compare the current identity value with the highest value in the table:

DBCC CHECKIDENT (N'dbo.Orders', NORESEED);

SELECT IDENT_CURRENT(N'dbo.Orders') AS current_identity,
       MAX(OrderId) AS max_id
FROM dbo.Orders;

When current_identity is lower than max_id, the next inserts will collide. In our test, each failed insert still consumed an identity value, so the seed crept forward one failure at a time and the error went away on its own later, which makes this cause easy to misread as random. DBCC CHECKIDENT (N'dbo.Orders', RESEED); with no value moves the seed up to the current maximum when it is lower, and the next insert succeeded.

Step 5: fix the check-then-insert race

If the duplicate arrived from another session moments earlier, the cause is almost always code like this:

IF EXISTS (SELECT 1 FROM dbo.Customer WHERE CustomerId = @CustomerId)
    UPDATE dbo.Customer SET Email = @Email WHERE CustomerId = @CustomerId;
ELSE
    INSERT dbo.Customer (CustomerId, Email) VALUES (@CustomerId, @Email);

Two sessions can both run the EXISTS check, both see no row, and both insert. The second one gets Msg 2627. Wrapping it in a transaction does not help on its own, because under the default READ COMMITTED level the check releases its shared lock straight away. It rarely shows up in development and appears under production concurrency.

The fix is to lock the key, or the gap where the key would go, until the transaction ends. This is the pattern in SQL Rig's proc-idempotent-upsert.sql:

CREATE OR ALTER PROCEDURE dbo.Customer_Upsert
    @CustomerId int, @Email nvarchar(256), @DisplayName nvarchar(100) = NULL
AS
BEGIN
    SET NOCOUNT ON; SET XACT_ABORT ON;
    BEGIN TRY
        BEGIN TRANSACTION;
        UPDATE dbo.Customer WITH (UPDLOCK, SERIALIZABLE)
           SET Email = @Email, DisplayName = @DisplayName, UpdatedAt = SYSDATETIME()
         WHERE CustomerId = @CustomerId
           AND (Email <> @Email OR ISNULL(DisplayName, N'') <> ISNULL(@DisplayName, N''));

        IF @@ROWCOUNT = 0 AND NOT EXISTS (SELECT 1 FROM dbo.Customer WITH (UPDLOCK, SERIALIZABLE)
                                          WHERE CustomerId = @CustomerId)
            INSERT dbo.Customer (CustomerId, Email, DisplayName)
            VALUES (@CustomerId, @Email, @DisplayName);
        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
        THROW;
    END CATCH;
END;

SERIALIZABLE takes a key-range lock even when the row does not exist yet, and UPDLOCK makes a second session wait at that point instead of reading past it. The second caller then finds the row and updates it. The extra condition on the UPDATE skips writes that would change nothing, so calling the procedure twice with the same values leaves one unchanged row.

This only works if the key column is indexed, which a primary key always is. On a column with no index, the range lock covers far more of the table and blocking goes up. It also does not protect a different unique index: two customers with different IDs and the same email still get Msg 2601, and that is a data problem to send back to the caller, not a race to retry.

We ran both versions on SQL Server 2022 with eight sessions upserting the same 5,000 new keys at the same time, several times over. The IF EXISTS version raised Msg 2627 on a small fraction of calls in every run. The locked version raised no errors and no deadlocks, and all 5,000 keys were present afterwards. Your rate will depend on load, so test with your own concurrency.

Step 6: if you use MERGE, add HOLDLOCK

MERGE looks atomic but has the same race. In the same test, a plain MERGE upsert raised Msg 2627 more often than the IF EXISTS version. With a HOLDLOCK hint on the target it raised none:

MERGE dbo.Customer WITH (HOLDLOCK) AS t
USING (SELECT @CustomerId AS CustomerId, @Email AS Email, @DisplayName AS DisplayName) AS s
   ON t.CustomerId = s.CustomerId
WHEN MATCHED AND (t.Email <> s.Email OR ISNULL(t.DisplayName, N'') <> ISNULL(s.DisplayName, N'')) THEN
    UPDATE SET Email = s.Email, DisplayName = s.DisplayName, UpdatedAt = SYSDATETIME()
WHEN NOT MATCHED BY TARGET THEN
    INSERT (CustomerId, Email, DisplayName) VALUES (s.CustomerId, s.Email, s.DisplayName);

Leave out WHEN NOT MATCHED BY SOURCE THEN DELETE; an upsert should never delete. The pack prefers the UPDATE-then-INSERT form for single-row OLTP upserts, because MERGE has a history of bugs with filtered indexes, triggers, and indexed views.

Whichever form you use, keep errors visible. Do not wrap the insert in a TRY block that swallows 2627, and do not read with NOLOCK to decide whether a row exists. If the procedure is called from a SQL Server Agent job, the Agent job failure guide shows where the error lands in job history, and if the locked version starts to block under load, the head blocker guide shows how to see who is waiting on whom.