Resources / PostgreSQL Tutorial

MERGE

MERGE explained with practical SQL patterns, edge cases, and production-ready guidance.

10 min read

Spin up a Postgres database in 20 seconds with Vela.

Try Vela Sandbox

MERGE in Modifying Data helps you write SQL that is easier to test, review, and operate at scale.

Introduction to MERGE

Use MERGE to change data safely with predictable write behavior.

Commonly paired with: SELECT, FROM, ORDER BY, DISTINCT.

Practical examples with MERGE in PostgreSQL

Reference pattern: start from canonical syntax and keep it explicit.

MERGE INTO inventory i
USING incoming_inventory s
ON i.sku = s.sku
WHEN MATCHED THEN UPDATE SET quantity = s.quantity
WHEN NOT MATCHED THEN INSERT (sku, quantity) VALUES (s.sku, s.quantity);

Production-style scenario: apply the same concept to realistic application data.

BEGIN;
UPDATE inventory SET quantity = quantity - 1 WHERE sku = 'sku_123';
INSERT INTO inventory_audit (sku, change_reason) VALUES ('sku_123', 'purchase');
COMMIT;

Additional example: use a variation to validate behavior and edge cases.

BEGIN;
INSERT INTO audit_log (event_type, payload)
VALUES ('data_change', jsonb_build_object('table', 'orders'));
COMMIT;

Production tips

  • Prefer explicit column lists and deterministic ordering when results feed APIs or batch jobs.
  • Validate plans with EXPLAIN before adding indexes, then re-check after schema changes.
  • Keep DDL, data backfills, and cleanups in transactions when possible to avoid partial state.
  • Use isolated environments for risky changes so query tuning and schema experiments stay safe.

Vela workflow tip

Test this pattern in an isolated branch database, share the result with your team, and promote only after query plans and row counts look correct.

Reference: PostgreSQL official documentation.

Continue through the next items in Modifying Data: Back to tutorial overview .

Related: INSERT INSERT Multiple Rows UPDATE