IC Improve Code Recipes

Recipe 2.3 · C#

Upserts Done Safely

Problem

"Insert the row, or update it if it already exists" is one of the most common requirements in business data. The obvious implementation has a race condition that only shows up under concurrent load, typically as a primary key violation in the middle of a busy import.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

SQL
-- Not to copy: check-then-act race condition.
IF EXISTS (SELECT 1 FROM ProductPrice WHERE Sku = @Sku)
    UPDATE ProductPrice
    SET Price = @Price, EffectiveDate = @EffectiveDate
    WHERE Sku = @Sku
ELSE
    INSERT INTO ProductPrice (Sku, Price, EffectiveDate)
    VALUES (@Sku, @Price, @EffectiveDate)

Two sessions run this for the same new SKU at the same moment. Both run the EXISTS check, both see no row, both insert. One fails with a key violation, or, if there is no unique constraint, the table now has two prices for one SKU.

The improved recipe

SQL
CREATE OR ALTER PROCEDURE dbo.ProductPrice_Upsert
    @Sku           VARCHAR(40),
    @Price         DECIMAL(19, 4),
    @EffectiveDate DATE
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    BEGIN TRANSACTION;

    UPDATE dbo.ProductPrice WITH (UPDLOCK, SERIALIZABLE)
    SET    Price         = @Price,
           EffectiveDate = @EffectiveDate,
           ModifiedUtc   = SYSUTCDATETIME()
    WHERE  Sku = @Sku;

    IF @@ROWCOUNT = 0
    BEGIN
        INSERT INTO dbo.ProductPrice
            (Sku, Price, EffectiveDate, ModifiedUtc)
        VALUES
            (@Sku, @Price, @EffectiveDate, SYSUTCDATETIME());
    END;

    COMMIT TRANSACTION;
END;

The set-based version, for loading a staging table such as the one filled by SqlBulkCopy in Chapter 1:

SQL
CREATE OR ALTER PROCEDURE dbo.ProductPrice_MergeFromStaging
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    BEGIN TRANSACTION;

    UPDATE p
    SET    p.Price         = s.Price,
           p.EffectiveDate = s.EffectiveDate,
           p.ModifiedUtc   = SYSUTCDATETIME()
    FROM   dbo.ProductPrice AS p WITH (UPDLOCK, SERIALIZABLE)
    JOIN   staging.PriceImport AS s ON s.Sku = p.Sku;

    INSERT INTO dbo.ProductPrice
        (Sku, Price, EffectiveDate, ModifiedUtc)
    SELECT s.Sku, s.Price, s.EffectiveDate, SYSUTCDATETIME()
    FROM   staging.PriceImport AS s
    WHERE  NOT EXISTS
           (
               SELECT 1
               FROM   dbo.ProductPrice AS p WITH (UPDLOCK, SERIALIZABLE)
               WHERE  p.Sku = s.Sku
           );

    COMMIT TRANSACTION;
END;

How it works

The UPDLOCK and SERIALIZABLE hints make the UPDATE take a key-range lock on the Sku value, even when no row exists yet. A second session that tries the same SKU waits at its own UPDATE until the first transaction commits. When it continues, it finds the row and updates it. No duplicates, no key violation, and no retry loop.

Updating first is also the faster path when most calls are updates, which is usually the case: one statement instead of a check plus a statement.

SET XACT_ABORT ON means any error rolls back the transaction automatically, so this short procedure does not need the full TRY/CATCH from Recipe 2.1. Add it if you want to log or translate errors.

The staging version applies the same idea to whole sets: update the rows that match, then insert the rows that do not, inside one transaction with the same hints.

Variations and pitfalls

  • You still need a unique constraint. The locking prevents the race in this procedure. A unique index on Sku prevents duplicates from every other code path, too.
  • Duplicates in staging. If the staging table has the same SKU twice, the insert adds both or the update applies one at random. Deduplicate first, for example by keeping the latest row per SKU with ROW_NUMBER().
  • MERGE. The single-statement alternative is MERGE, shown below.
SQL
MERGE dbo.ProductPrice WITH (HOLDLOCK) AS t
USING (VALUES (@Sku, @Price, @EffectiveDate))
      AS s (Sku, Price, EffectiveDate)
   ON t.Sku = s.Sku
WHEN MATCHED THEN
    UPDATE SET t.Price         = s.Price,
               t.EffectiveDate = s.EffectiveDate,
               t.ModifiedUtc   = SYSUTCDATETIME()
WHEN NOT MATCHED BY TARGET THEN
    INSERT (Sku, Price, EffectiveDate, ModifiedUtc)
    VALUES (s.Sku, s.Price, s.EffectiveDate, SYSUTCDATETIME());

The MERGE version needs HOLDLOCK for exactly the same race, it must end with a semicolon, and over the years it has had a list of bugs involving triggers, filtered indexes and indexed views. I use it in deployment scripts for reference data, where nothing runs concurrently. For application upserts I use update-then-insert, which every developer can read and debug. * Do not catch the key violation and retry. It works, but it turns a normal event into an exception, and under load it retries a lot.