SQL Upsert with ON CONFLICT and RETURNING
Implement a PostgreSQL upsert that restocks existing inventory, inserts new SKUs, and rejects stale writes using a version guard.
Code
-- Schema assumptions (PostgreSQL 15+):
-- inventory(sku text PRIMARY KEY, quantity integer NOT NULL CHECK (quantity >= 0),
-- price_cents integer NOT NULL CHECK (price_cents >= 0),
-- version integer NOT NULL DEFAULT 1,
-- updated_at timestamptz NOT NULL DEFAULT now())
-- The TEMP table below mirrors that shape; no external service is required.
CREATE TEMP TABLE inventory (
sku text PRIMARY KEY,
quantity integer NOT NULL CHECK (quantity >= 0),
price_cents integer NOT NULL CHECK (price_cents >= 0),
version integer NOT NULL DEFAULT 1,
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO inventory (sku, quantity, price_cents, version) VALUES
('KB-01', 10, 4900, 1),
('MS-02', 4, 2500, 1);
-- One statement handles both paths: `excluded` is the proposed row.
-- Existing SKUs add incoming stock; new SKUs are inserted untouched.
INSERT INTO inventory AS inv (sku, quantity, price_cents, version)
VALUES
('KB-01', 12, 5200, 1),
('MS-02', 1, 2400, 1),
('HD-03', 7, 8900, 1)
ON CONFLICT (sku) DO UPDATE
SET quantity = inv.quantity + EXCLUDED.quantity,
price_cents = EXCLUDED.price_cents,
version = inv.version + 1,
updated_at = now()
WHERE EXCLUDED.version = inv.version
RETURNING sku, quantity, price_cents, version;
-- A stale writer carries version 0. It matches no current row, so the
-- update is skipped and RETURNING yields zero rows instead of overwriting.
INSERT INTO inventory AS inv (sku, quantity, price_cents, version)
VALUES ('KB-01', 5, 1, 0)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
price_cents = EXCLUDED.price_cents,
updated_at = now()
WHERE EXCLUDED.version = inv.version
RETURNING sku, quantity, price_cents, version;What the code does
What runs here is INSERT / UPDATE / CREATE — inventory and set are the objects involved.
inventory is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.
Breaking the statements into their working parts: a WHERE clause constraining which rows the statement operates on; 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; a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns.
Using it
It carries its own setup: the session-local tables in play (inventory) come from the file’s statements — run the entire file against a disposable database.
Key statements
INSERT INTO inventory AS inv (sku, quantity, price_cents, version)
VALUES ('KB-01', 5, 1, 0)
ON CONFLICT (sku) DO UPDATE
SET quantity = EXCLUDED.quantity,
price_cents = EXCLUDED.price_cents,
updated_at = now()
WHERE EXCLUDED.version = inv.version
RETURNING sku, quantity, price_cents, version;
CREATE TEMP TABLE inventory (
sku text PRIMARY KEY,
quantity integer NOT NULL CHECK (quantity >= 0),
price_cents integer NOT NULL CHECK (price_cents >= 0),
version integer NOT NULL DEFAULT 1,
updated_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO inventory (sku, quantity, price_cents, version) VALUES
('KB-01', 10, 4900, 1),
('MS-02', 4, 2500, 1);
Interactive Tools for This Topic
FAQ
- Which tables or CTEs does it reference?
- The references are `inventory`, `set`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.