Deviopath › PostgreSQL

Sync a Product Feed With MERGE

Hard · Upsert

MERGE INTO target USING source ON condition compares two tables and runs a different action per case: WHEN MATCHED [AND cond] THEN UPDATE/DELETE, WHEN NOT MATCHED [BY TARGET] [AND cond] THEN INSERT, and WHEN NOT MATCHED BY SOURCE THEN UPDATE/DELETE for target rows missing from the source. The first WHEN that fits a row wins.

product_feed is the supplier's full, current catalog. Sync it into products (match on sku):

- In both, discontinued in the feed: set active = false (keep the old name and price). - In both, not discontinued: copy name and price, and set active = true. - Only in the feed, not discontinued: insert it as active. - Only in the feed, discontinued: ignore it. - Only in products (missing from the feed): set active = false.

Next: Transfers With Savepoints