sqlintermediate
MERGE / UPSERT Statement
Use MERGE or INSERT ON CONFLICT to upsert rows in a single statement.
sqlPress ⌘/Ctrl + Shift + C to copy
-- PostgreSQL: INSERT ... ON CONFLICT (upsert)
INSERT INTO products (sku, name, price, updated_at)
VALUES ('ABC-123', 'Widget', 29.99, NOW())
ON CONFLICT (sku)
DO UPDATE SET
name = EXCLUDED.name,
price = EXCLUDED.price,
updated_at = EXCLUDED.updated_at;
-- SQL Server / Oracle: MERGE
MERGE INTO products AS target
USING staging AS source
ON target.sku = source.sku
WHEN MATCHED THEN
UPDATE SET
name = source.name,
price = source.price
WHEN NOT MATCHED THEN
INSERT (sku, name, price)
VALUES (source.sku, source.name, source.price);Use Cases
- Syncing data from staging tables
- Idempotent data loads
- ETL pipelines
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
sqlintermediate
SQL Upsert and Merge Patterns
Insert or update records atomically using ON CONFLICT, MERGE, and database-specific upsert syntax.
Best for: Syncing data from external sources
#sql#upsert
sqlintermediate
SQL MERGE (Standard Upsert)
Use the SQL MERGE statement for atomic insert-or-update operations with matched/not-matched clauses.
Best for: Data warehouse loading
#merge#upsert
sqladvanced
Upsert - Technique 42
Insert or update rows
Best for: database operations
#sql#database
sqlbeginner
Merge - Technique 43
Merge source into target
Best for: database operations
#sql#database