Skip to content
tezvyn:
Menu

Design a SQL upsert from a staging table

Source: interviewMediumHow cards are made

Summary

knowledge of idempotent loads.

Key points

define a stable key, use MERGE or INSERT ON CONFLICT, dedupe the staging set first, run in a transaction.

Watch out for

a naive INSERT that duplicates or a delete-then-insert race.

What's really being asked

Whether you can design a daily load that is idempotent, meaning rerunning it produces the same result, and that correctly separates new records from updates without creating duplicates or losing rows on partial failure.

The full answer

First define the key that identifies a record uniquely, ideally a primary or natural business key, not a surrogate that changes each load. Deduplicate the staging table before merging, because the same key can arrive twice in one batch; keep only the latest version per key using a window function such as ROW_NUMBER partitioned by the key and ordered by a timestamp. Then perform the upsert. In SQL Server or Oracle use MERGE, matching staging to production on the key, with WHEN MATCHED THEN UPDATE and WHEN NOT MATCHED THEN INSERT. In Postgres use INSERT ... ON CONFLICT (key) DO UPDATE, and in MySQL use INSERT ... ON DUPLICATE KEY UPDATE. Wrap the operation in a transaction so a mid-batch failure rolls back cleanly.

The mistakes people make

A bare INSERT that duplicates existing rows, or a delete-then-insert pattern that leaves the table empty if the insert fails after the delete. Forgetting to dedupe staging, which causes MERGE to error or apply nondeterministic updates.

What usually comes next

How do you handle soft deletes from the source? What about concurrent loads hitting the same rows? How would you track which rows changed for downstream consumers?

A concrete example

A nightly job loads orders into staging. The analyst runs ROW_NUMBER over order_id ordered by updated_at descending and keeps rank one, then issues a single MERGE into the production orders table on order_id, updating status and amount for matches and inserting brand-new orders, inside one transaction so a crash leaves production untouched.

Interview question

Before running MERGE, why deduplicate the staging table so only one row per key remains?

  • a.Without it, the primary key on production is automatically dropped
  • b.Duplicate source keys make the UPDATE nondeterministic or cause the MERGE to errorCorrect
  • c.Deduplication is required to create the transaction
  • d.MERGE runs faster on sorted input regardless of duplicates
Why?

MERGE expects at most one source row per target key; multiple rows make which value wins nondeterministic or raise an error. Speed and transactions are unrelated reasons.

Just read this? Test yourself on what you have been reading.

Read the original → learn.microsoft.com

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on sql — each one lists the topics its interview covers.

See open roles