Merge Not Matched By Source Sync
PostgreSQL 17 MERGE adds WHEN NOT MATCHED BY SOURCE, so one statement updates changed rows, inserts missing ones, and deletes stale target rows in a sync.
Code
-- PostgreSQL 17 的 MERGE 新增 WHEN NOT MATCHED BY SOURCE:
-- 目标里有、源里没有的行直接删除——一条语句完成全量同步
CREATE TABLE price_list (sku text PRIMARY KEY, cents int NOT NULL);
CREATE TABLE feed (sku text PRIMARY KEY, cents int NOT NULL);
INSERT INTO price_list VALUES ('mug', 1200), ('cap', 900), ('bag', 2500);
INSERT INTO feed VALUES ('mug', 1350), ('bag', 2300), ('hat', 1500);
MERGE INTO price_list t
USING feed s
ON t.sku = s.sku
WHEN MATCHED AND t.cents <> s.cents THEN UPDATE SET cents = s.cents
WHEN NOT MATCHED BY TARGET THEN INSERT (sku, cents) VALUES (s.sku, s.cents)
WHEN NOT MATCHED BY SOURCE THEN DELETE;
SELECT * FROM price_list ORDER BY sku;Inside the snippet
Several statements share this file — SELECT / INSERT / UPDATE / DELETE / CREATE, with price_list, feed and set among the objects involved.
Mechanically, the statements are built from: an ORDER BY that fixes the output order; an upsert guard (ON CONFLICT/MERGE) that turns insert-or-update into one atomic statement; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Using it
Run it in the price_list database context.
Key statements
MERGE INTO price_list t
USING feed s
ON t.sku = s.sku
WHEN MATCHED AND t.cents <> s.cents THEN UPDATE SET cents = s.cents
WHEN NOT MATCHED BY TARGET THEN INSERT (sku, cents) VALUES (s.sku, s.cents)
WHEN NOT MATCHED BY SOURCE THEN DELETE;
INSERT INTO price_list VALUES ('mug', 1200), ('cap', 900), ('bag', 2500);
INSERT INTO feed VALUES ('mug', 1350), ('bag', 2300), ('hat', 1500);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SPDX License LookupSearch common SPDX license identifiers and see permissions, conditions, limitations, copyleft strength, and OSI or FSF approval status.
FAQ
- Which tables does this file reference?
- `price_list`, `feed`, `set` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.