🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

MERGE/UPSERT Patterns: Idempotent Inserts, Conflict Resolution

Advanced SQLMERGE/UPSERT⭐ Premium

Interview Question: "Explain the difference between INSERT ON CONFLICT and MERGE. How do you implement idempotent upserts? What are the race conditions in concurrent upserts?" — Asked at Amazon, Netflix, Spotify for Backend Engineer roles

â„šī¸

Difficulty: Advanced | Companies: Amazon, Netflix, Spotify, Uber, Airbnb | Time: 45-60 minutes

What an upsert has to guarantee

An upsert is one statement that either inserts a row or updates the one already there, and its value comes from the guarantee it makes while other sessions are writing. Without that guarantee, two services loading the same inventory feed produce duplicate keys, lost updates, or a transaction that aborts half-way and leaves a count that changed for no visible reason. Three properties deserve to be kept apart: atomicity, meaning the check and the write are one indivisible step; idempotency, meaning running the same load twice leaves the same state; and conflict policy, meaning what happens when the incoming row disagrees with the stored one. This lesson works through the standard MERGE, the PostgreSQL and MySQL dialects, and the concurrency traps that appear only when two sessions touch the same key within the same second.

MERGE Statement (SQL:2008 Standard)

MERGE provides atomic INSERT/UPDATE/DELETE operations:

-- Create target table
CREATE TABLE product_inventory (
    product_id INT PRIMARY KEY,
    product_name VARCHAR(100),
    quantity INT,
    last_updated TIMESTAMP,
    version INT DEFAULT 1
);

-- Create source table (staging)
CREATE TABLE inventory_staging (
    product_id INT,
    product_name VARCHAR(100),
    quantity INT
);

-- Insert initial data
INSERT INTO product_inventory VALUES
(1, 'Laptop', 50, CURRENT_TIMESTAMP, 1),
(2, 'Mouse', 200, CURRENT_TIMESTAMP, 1),
(3, 'Keyboard', 150, CURRENT_TIMESTAMP, 1);

-- Insert staging data
INSERT INTO inventory_staging VALUES
(1, 'Laptop', 45),  -- Update (decrease)
(2, 'Mouse', 180),  -- Update (decrease)
(4, 'Monitor', 30); -- Insert (new)

-- Standard MERGE operation
MERGE INTO product_inventory AS target
USING inventory_staging AS source
ON target.product_id = source.product_id
WHEN MATCHED AND source.quantity != target.quantity THEN
    UPDATE SET 
        quantity = source.quantity,
        last_updated = CURRENT_TIMESTAMP,
        version = target.version + 1
WHEN MATCHED AND source.quantity = target.quantity THEN
    DO NOTHING
WHEN NOT MATCHED THEN
    INSERT (product_id, product_name, quantity, last_updated)
    VALUES (source.product_id, source.product_name, source.quantity, CURRENT_TIMESTAMP);

-- Verify results
SELECT * FROM product_inventory ORDER BY product_id;

Output:

product_idproduct_namequantitylast_updatedversion
1Laptop452024-06-15 10:30:002
2Mouse1802024-06-15 10:30:002
3Keyboard1502024-01-01 10:00:001
4Monitor302024-06-15 10:30:001

MERGE reads like the specification itself: match on a key, then update, insert, or do nothing, with each branch carrying its own condition. The cost of that expressiveness is subtle behaviour at the boundary. The standard says a target row may be matched at most once, so a source containing the same key twice raises an error in some engines and silently processes only the first row in others — deduplicate the source with a group by before merging, and the difference stops mattering. Notice that the update branch bumps a version column, which turns the merge into an optimistic write: a reader that later compares versions discovers its view is stale instead of trusting a value that changed underneath it.

PostgreSQL UPSERT (ON CONFLICT)

-- Basic ON CONFLICT DO UPDATE
INSERT INTO product_inventory (product_id, product_name, quantity, last_updated)
VALUES (1, 'Laptop', 40, CURRENT_TIMESTAMP)
ON CONFLICT (product_id) DO UPDATE
SET 
    quantity = EXCLUDED.quantity,
    last_updated = EXCLUDED.last_updated,
    version = product_inventory.version + 1;

-- ON CONFLICT DO NOTHING
INSERT INTO product_inventory (product_id, product_name, quantity, last_updated)
VALUES (5, 'Webcam', 25, CURRENT_TIMESTAMP)
ON CONFLICT DO NOTHING;

-- Conditional upsert
INSERT INTO product_inventory (product_id, product_name, quantity, last_updated)
VALUES (1, 'Laptop', 40, CURRENT_TIMESTAMP)
ON CONFLICT (product_id) DO UPDATE
SET 
    quantity = CASE 
        WHEN EXCLUDED.quantity > product_inventory.quantity 
        THEN EXCLUDED.quantity 
        ELSE product_inventory.quantity 
    END,
    last_updated = CURRENT_TIMESTAMP
WHERE EXCLUDED.quantity > product_inventory.quantity;

-- Upsert with subquery
INSERT INTO product_inventory (product_id, product_name, quantity, last_updated)
SELECT 
    product_id,
    product_name,
    quantity,
    CURRENT_TIMESTAMP
FROM inventory_staging
ON CONFLICT (product_id) DO UPDATE
SET 
    quantity = EXCLUDED.quantity,
    last_updated = EXCLUDED.last_updated;

PostgreSQL reaches the same destination with an upsert that names its conflict target: state the column or index that arbitrated, then either do nothing or update using values from the reserved pseudo-row holding the row that would have been inserted. Naming the target is not ceremony — without it the engine may arbitrate on a different unique index than the one you meant, and the update fires for conflicts you never expected to see. The conditional form with a predicate on the update is how you express "only take the larger value", and it is the correct answer to a concurrent decrement far more often than an application-side read-then-write. Every form remains a single statement, so the read and the write cannot be interleaved by another session.

MySQL INSERT ... ON DUPLICATE KEY UPDATE

-- MySQL syntax
INSERT INTO product_inventory (product_id, product_name, quantity, last_updated)
VALUES (1, 'Laptop', 40, CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE
    quantity = VALUES(quantity),
    last_updated = VALUES(last_updated),
    version = version + 1;

-- With IF function
INSERT INTO product_inventory (product_id, product_name, quantity, last_updated)
VALUES (1, 'Laptop', 40, CURRENT_TIMESTAMP)
ON DUPLICATE KEY UPDATE
    quantity = IF(VALUES(quantity) > quantity, VALUES(quantity), quantity),
    last_updated = CURRENT_TIMESTAMP;

MySQL reaches the same destination with ON DUPLICATE KEY UPDATE, which fires on any unique key violation rather than on a named one. The difference is practical: with two unique indexes on the table you cannot say which conflict you are handling, and the column reference inside the assignment points at the row you tried to insert — deprecated in MySQL 8.0.20 in favour of a row alias, but the semantics did not change. For a straight replacement both dialects behave as last write wins. When the decision depends on the stored value, write the comparison into the assignment or into the conditional function, and remember that affected-rows distinguishes an update from a fresh insert only if the connection asks for it.

Idempotent Upsert Pattern

-- Create idempotency key table
CREATE TABLE idempotency_keys (
    idempotency_key UUID PRIMARY KEY,
    operation VARCHAR(100),
    result JSONB,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    expires_at TIMESTAMP
);

-- Idempotent upsert function
CREATE OR REPLACE FUNCTION idempotent_upsert(
    p_key UUID,
    p_operation VARCHAR,
    p_data JSONB
) RETURNS JSONB AS $$
DECLARE
    v_result JSONB;
    v_existing JSONB;
BEGIN
    -- Check if key exists and not expired
    SELECT result INTO v_existing
    FROM idempotency_keys
    WHERE idempotency_key = p_key
        AND expires_at > CURRENT_TIMESTAMP;
    
    IF FOUND THEN
        -- Return cached result
        RETURN v_existing;
    END IF;
    
    -- Execute operation
    BEGIN
        -- Your business logic here
        v_result := jsonb_build_object(
            'status', 'success',
            'data', p_data,
            'processed_at', NOW()
        );
        
        -- Store result
        INSERT INTO idempotency_keys (idempotency_key, operation, result, expires_at)
        VALUES (p_key, p_operation, v_result, CURRENT_TIMESTAMP + INTERVAL '24 hours');
        
        RETURN v_result;
    EXCEPTION
        WHEN OTHERS THEN
            v_result := jsonb_build_object(
                'status', 'error',
                'error', SQLERRM,
                'processed_at', NOW()
            );
            RETURN v_result;
    END;
END;
$$ LANGUAGE plpgsql;

Idempotency is a property of the request rather than of the SQL. The key table above stores the first result for a key and returns it on every replay, so a client that retries after a timeout sees the original answer instead of triggering a second side effect. Three details decide whether the scheme survives production: the key must be generated by the client and stable across retries, the expiry must outlast the retry window while still bounding table growth, and the key insert must sit in the same transaction as the work — otherwise two concurrent retries both pass the existence check and both execute. A unique constraint on the key is the backstop that converts the race into a clean retry.

Concurrent Upsert Race Conditions

-- Problem: Race condition without proper locking
-- Session 1:
BEGIN;
SELECT quantity FROM product_inventory WHERE product_id = 1;
-- Returns 45

-- Session 2:
BEGIN;
SELECT quantity FROM product_inventory WHERE product_id = 1;
-- Also returns 45

-- Session 1:
UPDATE product_inventory SET quantity = 45 - 10 WHERE product_id = 1;
COMMIT;

-- Session 2:
UPDATE product_inventory SET quantity = 45 - 5 WHERE product_id = 1;
COMMIT;
-- Result: quantity = 40, but should be 30!

-- Solution: Use SELECT FOR UPDATE
BEGIN;
SELECT quantity FROM product_inventory WHERE product_id = 1 FOR UPDATE;
-- Now Session 2 will block until Session 1 commits

UPDATE product_inventory SET quantity = quantity - 10 WHERE product_id = 1;
COMMIT;

The interleaving above is a lost update, and it is worth naming the mechanism precisely: both sessions read 45, each computes its own answer, and the second write overwrites the first while reporting success. Taking a row lock on the read forces the second session to wait, which fixes the symptom but holds the lock for the whole transaction. Alternatives suit different workloads: a single conditional update locks the row only for that statement, an optimistic version column turns the conflict into a retry the caller can observe, and a serializable isolation level catches the whole pattern at commit time. Choose from how often the same row is contended — a hot counter and a rarely touched profile deserve different answers.

Atomic Counter Pattern

-- Atomic increment/decrement
UPDATE product_inventory
SET quantity = quantity - 10
WHERE product_id = 1 AND quantity >= 10
RETURNING *;

-- With retry logic
DO $$
DECLARE
    v_attempts INT := 0;
    v_max_attempts INT := 3;
    v_success BOOLEAN := FALSE;
BEGIN
    WHILE v_attempts < v_max_attempts AND NOT v_success LOOP
        BEGIN
            UPDATE product_inventory
            SET quantity = quantity - 10
            WHERE product_id = 1 AND quantity >= 10;
            
            IF FOUND THEN
                v_success := TRUE;
            ELSE
                RAISE EXCEPTION 'Insufficient inventory';
            END IF;
        EXCEPTION
            WHEN serialization_failure OR deadlock_detected THEN
                v_attempts := v_attempts + 1;
                PERFORM pg_sleep(random() * 0.1);
        END;
    END LOOP;
    
    IF NOT v_success THEN
        RAISE EXCEPTION 'Failed after % attempts', v_max_attempts;
    END IF;
END $$;

The retry loop is the honest form of an atomic decrement: one conditional update either matches and reports the new row, or matches nothing and says why. Guarding the subtraction with a quantity floor prevents overselling without ever reading the value first, and returning the row gives the new state back without a second round trip. The exception handler matters as much as the statement — serialization failures and deadlocks are retriable, constraint violations are not, and a loop that retries without sleeping turns a transient conflict into a hot spin. Back off with jitter, because two sessions retrying on a fixed interval collide again on exactly the same tick.

Bulk UPSERT Pattern

-- Efficient bulk upsert
INSERT INTO product_inventory (product_id, product_name, quantity, last_updated)
SELECT 
    s.product_id,
    s.product_name,
    s.quantity,
    CURRENT_TIMESTAMP
FROM inventory_staging s
ON CONFLICT (product_id) DO UPDATE
SET 
    product_name = EXCLUDED.product_name,
    quantity = EXCLUDED.quantity,
    last_updated = EXCLUDED.last_updated,
    version = product_inventory.version + 1;

-- With batch processing
DO $$
DECLARE
    v_batch_size INT := 1000;
    v_rows_processed INT;
BEGIN
    LOOP
        INSERT INTO product_inventory (product_id, product_name, quantity, last_updated)
        SELECT 
            s.product_id,
            s.product_name,
            s.quantity,
            CURRENT_TIMESTAMP
        FROM inventory_staging s
        WHERE s.product_id NOT IN (
            SELECT product_id FROM product_inventory
            LIMIT v_batch_size
        )
        ON CONFLICT (product_id) DO UPDATE
        SET 
            quantity = EXCLUDED.quantity,
            last_updated = EXCLUDED.last_updated;
        
        GET DIAGNOSTICS v_rows_processed = ROW_COUNT;
        EXIT WHEN v_rows_processed = 0;
        
        RAISE NOTICE 'Processed % rows', v_rows_processed;
        COMMIT;
    END LOOP;
END $$;

Bulk upserts live or die on batch size. Too large and the transaction holds row locks and WAL volume long enough to delay vacuum and push replication lag; too small and commit overhead dominates and the job never finishes. A thousand to five thousand rows is the usual starting band, tuned against lock wait time rather than elapsed time alone. The batch loop above selects rows that are not yet present, which makes it an insert-only pass — a true bulk upsert should route the whole batch through the conflict clause and let the engine arbitrate, because filtering on membership in the target first turns a set operation into a correlated check per row and reintroduces exactly the per-row cost the batch was meant to avoid.

MERGE with Complex Logic

-- MERGE with multiple conditions
MERGE INTO product_inventory AS target
USING inventory_staging AS source
ON target.product_id = source.product_id
WHEN MATCHED AND source.quantity < target.quantity THEN
    UPDATE SET 
        quantity = target.quantity - (target.quantity - source.quantity),
        last_updated = CURRENT_TIMESTAMP,
        version = target.version + 1
WHEN MATCHED AND source.quantity > target.quantity THEN
    UPDATE SET 
        quantity = source.quantity,
        last_updated = CURRENT_TIMESTAMP,
        version = target.version + 1
WHEN MATCHED AND source.quantity = target.quantity THEN
    DO NOTHING
WHEN NOT MATCHED AND source.quantity > 0 THEN
    INSERT (product_id, product_name, quantity, last_updated)
    VALUES (source.product_id, source.product_name, source.quantity, CURRENT_TIMESTAMP)
WHEN NOT MATCHED AND source.quantity <= 0 THEN
    DO NOTHING;

Branch ordering decides correctness. Conditions are evaluated in the order written, so a catch-all matched branch placed ahead of the specific ones swallows them, and a row satisfying no branch simply does nothing — legal, silent, and rarely what the author intended. Notice that the arithmetic in the first branch collapses to the source quantity anyway, a reminder that clever expressions inside a merge frequently cancel themselves out; write the value you mean and let the reader see it. The zero-quantity guard on insert is another quiet decision: it stops negative staging rows from creating inventory that never existed, and that guard belongs in the statement rather than in a comment nobody reads during a reload.

Mathematical Properties

Idempotency property:

Upsert semantics:

Atomicity guarantee:

â„šī¸

Performance Tip: For bulk upserts, batch your operations (1000-5000 rows) to balance lock duration and transaction overhead.

Conflict Resolution Strategies

StrategyUse CaseImplementation
Last Write WinsSimple scenariosON CONFLICT DO UPDATE SET ... = EXCLUDED.
First Write WinsPreserve originalON CONFLICT DO NOTHING
MergeCombine valuesCustom logic in UPDATE
RejectStrict validationRAISE EXCEPTION
VersionOptimistic lockingWHERE version = EXCLUDED.version
-- Version-based conflict detection
INSERT INTO product_inventory (product_id, product_name, quantity, last_updated, version)
VALUES (1, 'Laptop', 40, CURRENT_TIMESTAMP, 1)
ON CONFLICT (product_id) DO UPDATE
SET 
    quantity = EXCLUDED.quantity,
    last_updated = EXCLUDED.last_updated,
    version = product_inventory.version + 1
WHERE product_inventory.version = EXCLUDED.version;

-- If version doesn't match, no update occurs
-- This prevents lost updates in concurrent scenarios

âš ī¸

Common Pitfall: Using EXCLUDED.* without checking can lead to overwriting changes made by other transactions. Always consider versioning for critical data.

Choosing a policy you can defend

Last write wins is correct only when concurrent writers never disagree about meaning — true for a heartbeat timestamp, false for an account balance. First write wins preserves an original the business cares about, such as the signup source that attributed the customer. Merging keeps both sides but needs a declared rule per column, and versioning pushes the decision to the caller, which is the only policy where the conflict becomes visible instead of silent. Whatever you choose, write it beside the table: an unstated policy degrades into last write wins by accident, and that is the version nobody can explain when the postmortem asks why the number moved.

Common Mistakes

Letting MERGE see duplicate keys in the source and assuming one wins

Fix: Deduplicate the source with a group by before the merge so each key appears once

Doing a read-then-write in the application to decrement a shared value

Fix: Use one conditional update with a floor predicate, or take a row lock before the read

Checking the idempotency key in a separate transaction from the work

Fix: Insert the key and perform the operation in the same transaction, backed by a unique constraint

Best Practices

  • Name the conflict target explicitly so arbitration cannot move to another unique index
  • Carry a version column on tables written by MERGE so staleness is detectable
  • Batch bulk loads in the one to five thousand row range and tune against lock wait time
  • Retry only retriable SQLSTATE classes, with jittered backoff and a hard attempt cap
  • Document the conflict policy next to the table instead of leaving it to reader habit

Interview Questions

Q1: MERGE versus INSERT ON CONFLICT?

MERGE is the standard multi-branch statement; ON CONFLICT is PostgreSQL's upsert with an explicit conflict target and access to the rejected row

Q2: What causes a lost update?

Two sessions read the same value and both write derived results, so the second overwrites the first without error; a row lock, a conditional update, or version checking prevents it

Q3: How do you make a nightly load idempotent?

Key each request, store its first result with a unique constraint, and run the work in the same transaction as the key insert

Q4: When does a bulk upsert become an N+1 pattern?

When the statement first checks membership in the target per row instead of letting the conflict clause arbitrate the whole batch

Key Takeaways

  • Upsert correctness is about atomicity, idempotency, and a stated conflict policy
  • MERGE branch order and duplicate source rows decide which branch actually runs
  • PostgreSQL arbitration follows the named conflict target, MySQL fires on any unique violation
  • Lost updates come from read-then-write; one conditional statement or a version column fixes them
  • Batch size and retry behaviour are part of the design, not tuning left for production
🔒

Premium Content

MERGE/UPSERT Patterns: Idempotent Inserts, Conflict Resolution

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-15

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement