Postgres UPDATE FROM: prove one source row per target
An updated-row count cannot prove that an ambiguous source applied the intended inventory change.
Quick answer
Postgres UPDATE FROM should join each target row to at most one source row. If several source rows match, PostgreSQL chooses one of them without a predictable winner. Decide whether those rows are additive events, competing replacements or invalid duplicates, then produce a unique source mapping before applying the update.
On this page
Postgres UPDATE FROM should join each target row to at most one source row. If several source rows match, PostgreSQL chooses one of them without a predictable winner. Decide whether those rows are additive events, competing replacements or invalid duplicates, then produce a unique source mapping before applying the update. [1]
What does an ambiguous UPDATE FROM actually do?#
It uses one matching join row for a target, with an unpredictable choice when the join is ambiguous. It does not promise to apply every matching source row in sequence. That difference can turn an apparently successful inventory update into a silently incomplete adjustment. PostgreSQL’s UPDATE reference states the cardinality requirement explicitly. [1]
A command tag showing an updated row is weak evidence here. It confirms a modification, not that the chosen source expressed the intended business change. If the same query appears to choose a consistent winner in a small test, that observation still does not create an ordering guarantee.
Decide whether each source row contributes a delta or replaces a stored value. An import may carry adjustments that must be summed. Another import may carry complete replacement quantities where only a designated revision is authoritative. A third may promise uniqueness and require rejection when that promise fails. Those cases need different SQL despite sharing the same join key.
Decide what an inventory adjustment means#
Scenario: a fictional warehouse has quantity 100 for SKU A and quantity 50 for SKU B. A sealed adjustment batch contains deltas of minus three and minus seven for A, and plus four for B. The required result is A at 90 and B at 54. Those are illustrative inputs and arithmetic, not warehouse measurements.
Use temporary tables in a disposable PostgreSQL session to explore the mechanism:
CREATE TEMP TABLE stock (
sku text PRIMARY KEY,
quantity bigint NOT NULL
);
CREATE TEMP TABLE adjustment (
event_id bigint PRIMARY KEY,
batch text NOT NULL,
sku text NOT NULL,
delta integer NOT NULL
);
INSERT INTO stock VALUES ('A', 100), ('B', 50);
INSERT INTO adjustment VALUES
(11, 'demo', 'A', -3),
(12, 'demo', 'A', -7),
(13, 'demo', 'B', 4);
-- Negative control: do not use this as the repair.
UPDATE stock AS s
SET quantity = s.quantity + a.delta
FROM adjustment AS a
WHERE a.batch = 'demo' AND a.sku = s.sku
RETURNING s.sku, s.quantity;Scenario: the ambiguous update can apply either adjustment for A, rather than their combined delta. Do not make a test assert a particular wrong winner. Assert that it fails the approved quantity of 90, then reset the disposable target before testing the repair. [1]
Count the source matches before rewriting anything. Group by the entire business key, including tenant, warehouse or account scope where applicable. Grouping only by a product label can merge adjustments that belong to different inventory owners. The key in this small example is deliberately narrower than a typical multi-tenant schema.
SELECT sku, count(*) AS source_rows, sum(delta) AS net_delta
FROM adjustment
WHERE batch = 'demo'
GROUP BY sku
ORDER BY sku;For additive events, grouping is the right operation because it preserves each accepted contribution in the total. DISTINCT over complete rows is not a substitute: two legitimate events can have equal deltas. Deduplicating repeated delivery requires an event identity before aggregation, otherwise the database cannot tell equal events from repeated copies of one event.
How do you freeze and validate the source mapping?#
Materialize the approved source set, enforce its key, and compare it with the target set before accepting the update. A preview query followed later by a mutation against a changing import table can read a different source population. At Read Committed, successive commands can observe newly committed changes. Being inside a transaction does not by itself make those separate reads identical. [4]
In this demonstration, a session-local temporary table freezes the deltas selected from the batch. In a production pipeline, use a durable sealed batch or an approved immutable mapping when work must survive a connection loss. Store the source boundary and event identities with the approval; a batch label that writers can continue appending to is not a sufficient boundary.
Use constraints as evidence of the mapping’s shape. A primary key on the materialized mapping enforces a unique non-null target identity. Keep quantities and deltas non-null when missing values represent invalid input. Otherwise an aggregation may conceal a missing event amount rather than report it as a validation failure. [2][3]
The target can change between preview and update too. If an operator previews quantities and another transaction modifies them, the preview is no longer the before-image the operator approved. Row locking can stabilize the selected target rows until the transaction ends. It cannot invent rows that do not exist, and it does not replace validation of the source set. [6]
Apply one additive delta per product#
The following continuation belongs in the same disposable session after resetting the sample stock quantities. It locks existing targets, records expected results, applies the unique mapping, and rejects an incomplete target set. Its final rollback is intentional so a rehearsal leaves the baseline available for another test.
UPDATE stock SET quantity = CASE sku WHEN 'A' THEN 100 ELSE 50 END;
BEGIN;
SET LOCAL lock_timeout = '2s';
CREATE TEMP TABLE approved_delta ON COMMIT DROP AS
SELECT sku, sum(delta) AS delta
FROM adjustment
WHERE batch = 'demo'
GROUP BY sku;
ALTER TABLE approved_delta ADD PRIMARY KEY (sku);
-- Lock the target rows before recording their before-images.
SELECT s.sku
FROM stock AS s JOIN approved_delta AS a USING (sku)
ORDER BY s.sku
FOR UPDATE OF s;
CREATE TEMP TABLE expected ON COMMIT DROP AS
SELECT s.sku, s.quantity AS before_quantity,
a.delta, s.quantity + a.delta AS after_quantity
FROM stock AS s JOIN approved_delta AS a USING (sku);
DO $$
BEGIN
IF NOT EXISTS (SELECT FROM approved_delta) THEN
RAISE EXCEPTION 'empty approved batch';
END IF;
IF (SELECT count(*) FROM expected) <>
(SELECT count(*) FROM approved_delta) THEN
RAISE EXCEPTION 'source contains an unknown target';
END IF;
END $$;
CREATE TEMP TABLE applied ON COMMIT DROP AS
WITH changed AS (
UPDATE stock AS s
SET quantity = e.after_quantity
FROM expected AS e
WHERE s.sku = e.sku
RETURNING s.sku, s.quantity
)
SELECT * FROM changed;
DO $$
BEGIN
IF EXISTS (
(SELECT sku, after_quantity FROM expected
EXCEPT SELECT sku, quantity FROM applied)
UNION ALL
(SELECT sku, quantity FROM applied
EXCEPT SELECT sku, after_quantity FROM expected)
) THEN
RAISE EXCEPTION 'applied mapping differs from approval';
END IF;
END $$;
SELECT e.sku, e.before_quantity, e.delta, a.quantity
FROM expected AS e JOIN applied AS a USING (sku)
ORDER BY e.sku;
ROLLBACK;This is a rehearsal pattern, not an automatic production repair. The expected quantity may exceed the target type’s range or violate a business rule such as nonnegative stock. Decide that rule before approving the mapping. A database constraint can enforce it, but the operator still needs a clear explanation of why a particular batch was rejected. [3]
Triggers, partitioning and concurrent operations can add behavior absent from these temporary tables. The RETURNING comparison examines rows reported by this update; it does not certify every downstream effect. Rehearse with the real schema’s triggers and constraints before changing a production acceptance condition. PostgreSQL documents the distinction between matched rows, modified rows and trigger-suppressed updates. [1]
What if the source contains replacement values?#
Choose an authoritative row rather than summing snapshots. If an inventory feed says the complete on-hand quantity was observed at different times, adding those observations would create stock that never existed. The selection rule must identify the intended observation and define how ties are resolved.
PostgreSQL’s DISTINCT ON can select a row per key when paired with suitable ordering. Its first row is unpredictable without an order that establishes the desired winner. An event identifier can break a tie only if the feed contract makes that tie-break meaningful; a convenient numeric identifier does not automatically mean “more authoritative.” [5]
-- Alternative source shape: complete replacement observations.
-- This is an illustrative selection query, not the additive lab.
SELECT DISTINCT ON (sku)
sku, observed_quantity, observed_at, observation_id
FROM inventory_observation
WHERE import_id = 'approved-import'
ORDER BY sku, observed_at DESC, observation_id DESC;Reject unresolved ambiguity when the source contract does not authorize a winner. For example, conflicting observations with the same business timestamp may represent a feed defect. Sorting until the SQL becomes deterministic can hide that defect. A repeatable wrong answer is still wrong.
| Source meaning | Suitable mapping | Failure to preserve |
|---|---|---|
| Independent deltas | Sum accepted events per complete key | Repeated delivery counted as another event |
| Authoritative replacement | Select by an agreed revision rule | Arbitrary tie-break presented as authority |
| Promised unique record | Enforce uniqueness and reject duplicates | Silently discarding a conflicting source row |
A scalar subquery offers another useful failure mode when uniqueness is required: multiple matches raise an error. But changing an UPDATE FROM into a scalar assignment also changes missing-match behavior. PostgreSQL documents that the scalar form can assign null when no source row exists, whereas the join form leaves an unmatched target alone. Preserve that choice explicitly. [1]
How do you verify and recover the batch?#
An empty batch deserves an explicit outcome. The lab rejects it because a repair operator expects a named change. A scheduled import may reasonably record “nothing to apply” instead. Preserve that distinction rather than coercing a missing aggregate into a zero adjustment and reporting a successful repair. PostgreSQL documents that aggregates such as SUM return null for an empty input. [2]
The before-image is useful for reconciliation, but an inverse delta is not automatically a safe rollback. Another valid stock movement may have occurred after the batch committed. A recovery procedure should identify the accepted events and current business state before proposing a compensating change. Keep that decision separate from an emergency attempt to run the same update in reverse.
Validate the join itself after constructing a unique source. A source key can be unique while a later join to an unconstrained lookup multiplies it again. Review the final relation consumed by UPDATE, including enrichment joins and tenant predicates. The one-source-row requirement applies at that mutation boundary, rather than only to an earlier staging table. [1]
Keep ignored records visible in the approval. An import filter may intentionally exclude a closed warehouse or an invalid observation, but the exclusion needs a reason tied to the original event. Otherwise the reduced source mapping can look internally correct while silently omitting part of the requested business change. Record accepted and rejected identities before treating a matching result set as proof of a complete batch.
The local rehearsal exercised the exact additive lab on PostgreSQL 17.11. It returned the approved quantities for both sample products and left the reset baseline after rollback. Separate controls rejected an unknown target, empty input and repeated event identity, and demonstrated the scalar-subquery missing-match difference. These checks establish behavior of the disposable example; production constraints and concurrent approval changes still require their own rehearsal.
Compare the approved keys and quantities with the rows the update returns. Compare the approved keys, before-values, deltas or winning observations, and returned after-values. Include a missing-target case, an empty input case, conflicting replacements and duplicated event delivery. Those tests expose different contract failures and deserve distinct outcomes.
The temporary mapping addresses source cardinality within one execution. It does not make an additive batch safe to replay after a lost commit acknowledgement. Reapplying an already committed delta can adjust stock again. A durable application receipt tied atomically to the update is a separate design requirement; the transactional outbox checklist discusses related transaction boundaries.
Treat a lock timeout or serialization failure as a failed transaction to reconcile, not permission to apply only the remaining rows. Preserve the approved source mapping and determine whether a prior execution committed. For lock-order concerns, use the deadlock investigation and transaction retry guide before adding increasingly broad retries.
Save the rehearsal query and its actual result with the approval. Document which PostgreSQL version and schema were exercised. A pure arithmetic test can establish the intended quantities, while only an executed database example establishes how this SQL behaves on that tested system. Neither result establishes production performance or replica impact.
What else should you verify?#
- Does UPDATE FROM apply every matching delta?
- No. When several source rows match a target, PostgreSQL uses one join row with an unpredictable choice. Aggregate accepted additive events or select an authoritative replacement first, then update from a source with the required cardinality. [1]
- Does DISTINCT remove duplicate events safely?
- Only when the chosen distinct key represents event identity. Equal deltas can belong to separate legitimate events. Define delivery deduplication before aggregation, then enforce the source mapping’s complete business key rather than discarding equal-looking rows. [2][3]
- Is a scalar subquery an equivalent repair?
- It can reject multiple matches, which is useful when uniqueness is required. However, a missing source match can assign null rather than leave the target unchanged. Test that behavior and any target constraints before replacing the join form. [1]
- Can a sealed batch be applied again after a timeout?
- Not merely because it is sealed. An additive update that already committed can apply its delta again. Reconcile the commit outcome and use a durable application receipt when the workflow requires replay protection; source uniqueness alone addresses a different problem.