MERGE Conditional Upsert With RETURNING Action

Run a conditional PostgreSQL MERGE that skips unchanged rows via DO NOTHING, updates or inserts diffs, and returns merge_action() per modified row.

SqlData Integrity

Code

snippet
-- PostgreSQL 17+ supports RETURNING and merge_action() inside MERGE
CREATE TEMP TABLE catalog_items (
    sku          text PRIMARY KEY,
    price_cents  integer NOT NULL,
    payload_hash text NOT NULL,
    revision     integer NOT NULL DEFAULT 1
);

CREATE TEMP TABLE incoming_batch (
    sku          text PRIMARY KEY,
    price_cents  integer NOT NULL,
    payload_hash text NOT NULL
);

INSERT INTO catalog_items VALUES
    ('kbd-1', 9900, 'h1', 1),
    ('mse-2', 4500, 'h2', 1);

INSERT INTO incoming_batch VALUES
    ('kbd-1', 9900, 'h1'),   -- unchanged: skipped by DO NOTHING
    ('mse-2', 4200, 'h2b'),  -- changed: updated
    ('pad-3', 1900, 'h3');   -- new: inserted

MERGE INTO catalog_items AS t
USING incoming_batch AS s
ON t.sku = s.sku
WHEN MATCHED AND t.payload_hash = s.payload_hash THEN
    DO NOTHING
WHEN MATCHED THEN
    UPDATE SET price_cents = s.price_cents,
               payload_hash = s.payload_hash,
               revision = t.revision + 1
WHEN NOT MATCHED THEN
    INSERT (sku, price_cents, payload_hash)
    VALUES (s.sku, s.price_cents, s.payload_hash)
RETURNING merge_action() AS action, t.sku, t.price_cents, t.revision;

Implementation flow — MERGE Conditional Upsert With RETURNING Action

INSERT / UPDATE / CREATE statements share the script, touching catalog_items, incoming_batch and set.

catalog_items and incoming_batch are created in this same file as session-local temp tables — nothing needs to exist beforehand, and they go away at session end.

In terms of clauses, the statements use: an upsert guard (ON CONFLICT/MERGE) that turns insert-or-update into one atomic statement; a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.

Applying it

It carries its own setup: the session-local tables in play (catalog_items, incoming_batch) come from the file’s statements — run the entire file against a disposable database.

Statements that matter

INSERT INTO incoming_batch VALUES
    ('kbd-1', 9900, 'h1'),   -- unchanged: skipped by DO NOTHING
    ('mse-2', 4200, 'h2b'),  -- changed: updated
    ('pad-3', 1900, 'h3');   -- new: inserted
CREATE TEMP TABLE catalog_items (
    sku          text PRIMARY KEY,
    price_cents  integer NOT NULL,
    payload_hash text NOT NULL,
    revision     integer NOT NULL DEFAULT 1
);
CREATE TEMP TABLE incoming_batch (
    sku          text PRIMARY KEY,
    price_cents  integer NOT NULL,
    payload_hash text NOT NULL
);

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`catalog_items`, `incoming_batch`, `set` — referenced directly, no join needed.