SQL MERGE (Standard Upsert)
Use the SQL MERGE statement for atomic insert-or-update operations with matched/not-matched clauses.
-- PostgreSQL 15+ MERGE syntax
MERGE INTO products AS target
USING staging_products AS source
ON target.sku = source.sku
WHEN MATCHED AND source.price <> target.price THEN
UPDATE SET
price = source.price,
updated_at = NOW()
WHEN NOT MATCHED THEN
INSERT (sku, name, price, created_at)
VALUES (source.sku, source.name, source.price, NOW())
WHEN NOT MATCHED BY SOURCE THEN
UPDATE SET
is_active = false;Use Cases
- Data warehouse loading
- Syncing external data
- Incremental updates
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
UPSERT with ON CONFLICT
Insert or update rows atomically using PostgreSQL ON CONFLICT clause with partial indexes and conditions.
Resolve Git Merge Conflicts
Step-by-step guide to identify, resolve, and complete merge conflict resolution in Git.
Python ETL Pipeline Example
Complete extract-transform-load pipeline with error handling, logging, and incremental processing.
Python Batch Processing Script
Process large files in configurable batches with progress tracking, error handling, and resume support.