UPDATE FROM RETURNING Emits Applied Deltas
Apply batch stock changes via UPDATE ... FROM with a non-negative guard and emit previous, delta, and resulting counts in one RETURNING clause.
Code
CREATE TEMP TABLE stock (
sku text PRIMARY KEY,
qty integer NOT NULL CHECK (qty >= 0)
);
CREATE TEMP TABLE stock_deltas (
sku text PRIMARY KEY,
delta integer NOT NULL
);
INSERT INTO stock VALUES ('mug', 10), ('hat', 2), ('bag', 5);
INSERT INTO stock_deltas VALUES ('mug', -3), ('hat', -5), ('bag', 4);
-- Only rows staying >= 0 update; RETURNING reads post-update qty and FROM delta
UPDATE stock AS s
SET qty = s.qty + d.delta
FROM stock_deltas AS d
WHERE s.sku = d.sku
AND s.qty + d.delta >= 0
RETURNING
s.sku,
(s.qty - d.delta) AS previous_qty,
d.delta,
s.qty AS updated_qty;
-- Verify 'hat' stayed untouched at qty=2
SELECT sku, qty FROM stock ORDER BY sku;Execution breakdown — UPDATE FROM RETURNING Emits Applied Deltas
SELECT / INSERT / UPDATE / CREATE statements share the script, touching stock and stock_deltas.
stock and stock_deltas are created in this same file as session-local temp tables — nothing needs to exist beforehand, and they go away at session end.
The pieces that do the work: a WHERE clause filtering the rows one statement applies to; an ORDER BY that fixes the output order; 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.
Putting it to use
Nothing outside the file is needed: the session-local tables it touches (stock, stock_deltas) are created by the file itself — point it at a scratch database and run the whole thing.
Core lines
UPDATE stock AS s
SET qty = s.qty + d.delta
FROM stock_deltas AS d
WHERE s.sku = d.sku
AND s.qty + d.delta >= 0
RETURNING
s.sku,
(s.qty - d.delta) AS previous_qty,
d.delta,
s.qty AS updated_qty;
CREATE TEMP TABLE stock (
sku text PRIMARY KEY,
qty integer NOT NULL CHECK (qty >= 0)
);
CREATE TEMP TABLE stock_deltas (
sku text PRIMARY KEY,
delta integer NOT NULL
);
Interactive Tools for This Topic
FAQ
- Which tables does the SQL touch?
- `stock`, `stock_deltas` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.