MERGE Statement — Complete Guide
MERGE Statement — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 55 of 100
MERGE Statement
SQL ✓ → Advanced
Advanced · 2 — Production · ~10 min · PostgreSQL — JSONB & Modern Features
What is this?
MERGE (PostgreSQL 15+) upserts in one statement — match source to target ON keys, WHEN MATCHED UPDATE, WHEN NOT MATCHED INSERT. Replaces brittle INSERT ON CONFLICT patterns for some ETL.
Why should you care?
PostgresVerse nightly inventory sync from warehouse file merges stock counts without separate UPDATE and INSERT scripts.
See it live — copy this example
Run in pgAdmin or psql.
MERGE INTO products AS t
USING staging_products AS s
ON t.product_id = s.product_id
WHEN MATCHED AND s.stock_qty IS DISTINCT FROM t.stock_qty THEN
UPDATE SET stock_qty = s.stock_qty, updated_at = now()
WHEN NOT MATCHED THEN
INSERT (product_id, name, stock_qty) VALUES (s.product_id, s.name, s.stock_qty);
What happened?
- staging_products drives merge.
- Matched rows update only if stock changed.
- Unmatched rows insert new products.
- One atomic statement.
Practice next
- Create staging_products with mix of existing and new ids.
- Run MERGE and compare products table.
- Add WHEN NOT MATCHED BY SOURCE DELETE for full sync (careful).
- Add AND s.deleted THEN DELETE branch for soft-delete sync.
- Compare row counts with INSERT ON CONFLICT DO UPDATE.
Remember
MERGE combines insert/update (and optional delete). IS DISTINCT FROM avoids noop updates. Requires PostgreSQL 15+.
PostgresVerse WMS sync
Warehouse management MERGE refreshes 50k SKUs every 15 minutes.
Outcome: Inventory accuracy improves; script lines cut in half.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!