Sub topic 7
When several rows match one target row
This chapter assumes you can write UPDATE ... FROM and DELETE ... USING statements and that you know how an inner join multiplies rows. It uses the products and price_updates tables from the schema introduced earlier in this tutorial.
Why this case deserves attention
A join between a target table and a source table can pair one target row with many source rows. A SELECT returns every pair. An UPDATE can't write several values into one row, so PostgreSQL needs a rule for that case.
The rule for UPDATE ... FROM is that each target row is updated at most once. If several joined rows match it, PostgreSQL uses one of them. The documentation states that which one is used is not readily predictable. The statement raises no error and no warning. It reports a normal row count.
Be careful with this rule. A wrong price can be written with no sign that anything went wrong.
Setting up an ambiguous case
This data gives product 1 two staging rows. Product 2 has one, and product 3 has none.
INSERT INTO products (id, name, price) VALUES
(1, 'Mug', 8.00),
(2, 'Plate', 12.00),
(3, 'Bowl', 10.00);
INSERT INTO price_updates (product_id, new_price, created_at) VALUES
(1, 9.00, '2026-11-01 09:00+00'),
(1, 9.50, '2026-11-02 09:00+00'),
(2, 13.00, '2026-11-01 09:00+00');Now run the plain statement from earlier in the tutorial:
UPDATE products AS p
SET price = u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id;PostgreSQL answers UPDATE 2. Three staging rows matched, but only two products changed. The count is the number of target rows updated, not the number of joined pairs. Product 1 now holds either 9.00 or 9.50. You can't tell which from the statement, and a different plan or a later vacuum can change the answer. Product 3 is untouched, because it has no match and the join is an inner join.
Detecting duplicates before you update
Before a bulk update, check whether the join key is unique in the source:
SELECT product_id, count(*) AS matches
FROM price_updates
GROUP BY product_id
HAVING count(*) > 1;An empty result means each product has at most one staging row, so the plain UPDATE ... FROM is deterministic. Any rows returned are the targets with ambiguous matches. If the source key is meant to be unique, enforce it with a constraint, so the problem can't return:
-- Only valid if each product should have a single pending update
ALTER TABLE price_updates
ADD CONSTRAINT price_updates_one_per_product UNIQUE (product_id);In a staging table that keeps history, duplicates are expected. Then you must choose a rule for which row wins.
Making the choice deterministic
Choose a rule such as "newest wins", "largest wins", or "sum them". Put the rule in a subquery so the join sees at most one row per target.
Newest row with DISTINCT ON
DISTINCT ON keeps the first row of each group, and the ORDER BY decides which row is first:
UPDATE products AS p
SET price = u.new_price
FROM (
SELECT DISTINCT ON (product_id) product_id, new_price
FROM price_updates
ORDER BY product_id, created_at DESC, new_price DESC
) AS u
WHERE u.product_id = p.id;The ORDER BY must start with the DISTINCT ON expressions. The extra new_price DESC breaks ties when two rows have the same created_at. Without a tie-breaker, ties bring back the arbitrary choice.
With the sample data, product 1 becomes 9.50 and product 2 becomes 13.00.
Aggregating to one row
If the rule is a summary, use GROUP BY. This sets each product to the highest proposed price:
UPDATE products AS p
SET price = u.max_price
FROM (
SELECT product_id, max(new_price) AS max_price
FROM price_updates
GROUP BY product_id
) AS u
WHERE u.product_id = p.id;Aggregation works well for rules like max, min, sum, or count. It can't pick a whole row. If you need several columns from the same winning row, use DISTINCT ON or a window function.
Ranking with a window function
row_number() does what DISTINCT ON does, and it also works in other databases:
UPDATE products AS p
SET price = u.new_price
FROM (
SELECT product_id, new_price,
row_number() OVER (
PARTITION BY product_id
ORDER BY created_at DESC, new_price DESC
) AS rn
FROM price_updates
) AS u
WHERE u.product_id = p.id
AND u.rn = 1;Correlated subquery in SET
A scalar subquery in SET returns one value per target row, and LIMIT 1 enforces that:
UPDATE products AS p
SET price = (
SELECT u.new_price
FROM price_updates AS u
WHERE u.product_id = p.id
ORDER BY u.created_at DESC, u.new_price DESC
LIMIT 1
)
WHERE EXISTS (
SELECT 1 FROM price_updates AS u WHERE u.product_id = p.id
);The EXISTS filter matters here. Without it, the subquery returns no rows for product 3, and price would be set to NULL. The column is NOT NULL, so the statement would fail with an error. On a nullable column it would silently erase data.
If you drop LIMIT 1 and a product has several matches, PostgreSQL raises more than one row returned by a subquery used as an expression. That behavior is stricter than UPDATE ... FROM, and it's useful when you want duplicates to stop the statement.
Choosing between the approaches
| Approach | Handles duplicates | Unmatched target rows | Best when |
|---|---|---|---|
| Plain `UPDATE ... FROM` | Picks one row arbitrarily | Left unchanged | The source key is unique |
| `DISTINCT ON` subquery | You choose by `ORDER BY` | Left unchanged | You need one whole row per key |
| Aggregating subquery | You choose by aggregate | Left unchanged | The rule is `max`, `sum`, and so on |
| `row_number()` subquery | You choose by `ORDER BY` | Left unchanged | You want portable SQL |
| Correlated subquery in `SET` | Errors, or `LIMIT 1` picks | Set to `NULL` without `EXISTS` | You want an error on duplicates |
Multiple matches in DELETE ... USING
For deletes, many matches are usually harmless. A target row is deleted once, however many joined rows match it. This statement removes each order once, even if the customer joined to it several times through a larger join:
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed';The only difference is the count in the command tag. DELETE 5 means five target rows were removed, not five joined pairs.
Ambiguity still matters for deletes when the condition itself depends on which match you consider. Suppose you join to a table of flags and want to delete only if all flags are set. A plain join deletes if any joined row passes. State "all" with NOT EXISTS instead.
Checking what actually happened
Use RETURNING to see the values written. It returns one row per updated target row, not per joined pair:
UPDATE products AS p
SET price = u.new_price
FROM (
SELECT DISTINCT ON (product_id) product_id, new_price
FROM price_updates
ORDER BY product_id, created_at DESC, new_price DESC
) AS u
WHERE u.product_id = p.id
RETURNING p.id, p.name, p.price;Compare the number of returned rows with the number of distinct keys in the source. If the plain version returns fewer rows than the source has, you have duplicates. To spot the problem before it writes anything, run the same join as a SELECT inside a transaction, as the previewing chapter shows, and look for target ids that appear more than once.
Common mistakes
- Assuming the row count equals the number of source rows. It counts target rows.
- Putting
ORDER BYandLIMITon the outerUPDATE. PostgreSQL doesn't support them there, and they wouldn't control which joined row is used anyway. - Using
DISTINCT ONwithout anORDER BY, or with anORDER BYthat doesn't start with theDISTINCT ONcolumns. The first case gives arbitrary rows. The second raises an error. - Leaving out a tie-breaker, so equal timestamps bring back nondeterminism.
- Using a correlated subquery in
SETwithoutEXISTS, which sets unmatched rows toNULL.
Exercise
The table priceupdates holds two rows for product 1 with the same createdat but different new_price values (9.00 and 9.50). Write an UPDATE ... FROM statement that sets each product to its newest price and, on a timestamp tie, to the higher price. Why is the second ORDER BY column needed?
Show answer
UPDATE products AS p SET price = u.newprice FROM (SELECT DISTINCT ON (productid) productid, newprice FROM priceupdates ORDER BY productid, createdat DESC, newprice DESC) AS u WHERE u.productid = p.id; The newprice DESC tie-breaker is needed because DISTINCT ON keeps the first row of each group, and when two rows tie on created_at the order between them is otherwise arbitrary, so the result would not be reproducible.
Exercise
A plain UPDATE ... FROM against products joins three staging rows to two products, and psql prints UPDATE 2. Which query would you run first to find the products that have ambiguous matches, and what does a non-empty result tell you?
Show answer
SELECT productid, count(*) FROM priceupdates GROUP BY productid HAVING count(*) > 1; A non-empty result lists the products that match more than one staging row. For those products the plain statement writes one arbitrary value, so you must choose a rule (DISTINCT ON, an aggregate, or rownumber) or add a unique constraint.