Sub topic 6
Avoiding the Duplicate-Source Error
Assume you know basic SELECT, joins, aggregates, primary keys, and transactions. This chapter focuses on one important MERGE rule: each target row may be matched by at most one source row.
Why duplicate source rows fail
MERGE compares a target table with a source query using the ON condition. PostgreSQL then chooses an action for each source row:
- A matching source row can update or delete one target row.
- A nonmatching source row can insert a new target row.
- A source row can also be skipped when a conditional
WHENclause does not apply.
The source must not contain multiple rows that match the same target row. Otherwise PostgreSQL cannot safely apply two actions to the same target row in one MERGE. It raises a cardinality error, commonly reported as:
ERROR: MERGE command cannot affect row a second timeFor example, suppose inventory contains one row for product 2:
| product_id | name | quantity |
|---|---|---|
| 2 | nut | 50 |
Now the source contains two changes for that product:
| product_id | name | delta |
|---|---|---|
| 2 | nut | 10 |
| 2 | nut | 25 |
Both source rows match inventory.product_id = 2. PostgreSQL will not guess whether the quantity should become 60, 75, or 85, nor will it silently apply two updates. You must define that rule in the source query.
flowchart TD
A[Source rows] --> B{Same product_id more than once?}
B -- No --> C[MERGE can match each target row once]
B -- Yes --> D[Deduplicate or aggregate source]
D --> E[One source row per product_id]
E --> CDetect duplicates before MERGE
Use GROUP BY and HAVING to find keys that appear more than once:
SELECT product_id, count(*) AS source_rows
FROM inventory_updates
GROUP BY product_id
HAVING count(*) > 1;This query does not change data. It identifies source keys that could match the same target row repeatedly. Run it when validating an import or diagnosing a failed synchronization.
You can also inspect the complete duplicate groups:
SELECT u.*
FROM inventory_updates AS u
JOIN (
SELECT product_id
FROM inventory_updates
GROUP BY product_id
HAVING count(*) > 1
) AS duplicates
ON duplicates.product_id = u.product_id
ORDER BY u.product_id;Aggregate changes into one row
When multiple source rows represent separate quantity changes, aggregate them before the MERGE. In this example, adding 10 and 25 produces one net change of 35.
MERGE INTO inventory AS t
USING (
SELECT
product_id,
max(name) AS name,
sum(delta) AS delta
FROM inventory_updates
GROUP BY product_id
) AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET
quantity = t.quantity + s.delta,
updated_at = now()
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);The derived table in USING produces exactly one row for each product_id. sum(delta) combines all changes. max(name) selects one name because the grouped result needs a single value. That choice is safe only if names for the same product are expected to agree.
If conflicting names are possible, do not hide the conflict with max. Detect it instead:
SELECT product_id
FROM inventory_updates
GROUP BY product_id
HAVING count(DISTINCT name) > 1;You can reject the import, correct the source data, or apply an explicit business rule.
Choose a deterministic deduplication rule
Aggregation is appropriate for additive data such as quantities or amounts. Other data needs a different rule.
To keep the newest event, use a window function. A window function calculates a value across related rows without collapsing them immediately.
WITH ranked_updates AS (
SELECT
u.*,
row_number() OVER (
PARTITION BY product_id
ORDER BY updated_at DESC, update_id DESC
) AS position
FROM inventory_updates AS u
)
MERGE INTO inventory AS t
USING (
SELECT product_id, name, delta
FROM ranked_updates
WHERE position = 1
) AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET
quantity = t.quantity + s.delta,
updated_at = now()
WHEN NOT MATCHED THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);The ORDER BY must be deterministic. If two rows have the same updated_at, update_id breaks the tie. Without a stable tie-breaker, PostgreSQL may choose different rows on different executions.
Validate the source contract
The best fix is often upstream. If the staging table should contain one row per product, enforce that rule with a unique constraint. If multiple events are valid, keep them in the staging table and deduplicate in the USING query.
A reliable workflow is:
- Identify the key used by the
ONcondition. - Check for duplicate source keys.
- Decide whether to sum, keep the newest row, reject conflicts, or use another rule.
- Make the
USINGquery return one row per target key. - Run
MERGEinside the transaction that loads the source.
The same principle applies to rows that do not yet exist in the target. Duplicate source keys can produce multiple attempted inserts for one key and may cause a unique-constraint violation. Source preparation prevents both kinds of failure.
Exercise
inventory_updates contains several rows for each product, and each delta is an independent quantity change. Which source expression should you use to avoid the duplicate-source error?
Show answer
Group by product_id, select one consistent name, and use sum(delta) so the MERGE receives one row per product.