Sub topic 6
Avoiding the duplicate-source error
This chapter assumes you can write a basic MERGE with WHEN MATCHED and WHEN NOT MATCHED clauses, and that you know how primary keys and GROUP BY work. It covers the error PostgreSQL raises when one target row is matched by several source rows, the related unique-violation that duplicates can cause on the insert side, and the usual ways to prepare a source so neither happens.
The rule: one source row per target row
MERGE joins the source to the target on your ON condition. For each target row that the join matches, PostgreSQL can apply at most one change in a single statement. If two source rows match the same target row and both would update or delete it, PostgreSQL stops with this error:
ERROR: MERGE command cannot affect row a second time
HINT: Ensure that not more than one source row matches any one target row.
SQLSTATE: 21000 (cardinality_violation)The reason is determinism. If two source rows say quantity = 10 and quantity = 99 for the same product, the final value would depend on the order the join happened to produce rows, which is not guaranteed. PostgreSQL refuses to guess. Identical values are rejected as well, because the check looks at row identity and does not compare values.
The error aborts the whole statement. Nothing is partially applied, so you can fix the source and rerun.
Reproducing the error
Start from a clean slate. This setup matches the earlier tables, with one extra row in the update feed that duplicates product 2:
DROP TABLE IF EXISTS inventory_updates;
DROP TABLE IF EXISTS inventory;
CREATE TABLE inventory (
product_id int PRIMARY KEY,
name text NOT NULL,
quantity int NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE inventory_updates (
product_id int,
name text,
delta int
);
INSERT INTO inventory (product_id, name, quantity) VALUES
(1, 'bolt', 100),
(2, 'nut', 50);
INSERT INTO inventory_updates (product_id, name, delta) VALUES
(2, 'nut', 25),
(2, 'nut', 10),
(3, 'washer', 40);Now run the simple merge directly against the staging table:
MERGE INTO inventory AS t
USING inventory_updates 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);Product 2 exists in inventory and appears twice in the source. The first match updates the row. The second match would update the same row again, so PostgreSQL raises the cardinality error and rolls back the statement.
Correction: the diagram belongs in a diagram fence. It follows here.
Finding the duplicates
Before changing the statement, look at the data. A grouped count on the join key shows which keys are duplicated:
SELECT product_id, count(*) AS source_rows
FROM inventory_updates
GROUP BY product_id
HAVING count(*) > 1;For the sample data this returns product 2 with 2 source rows. If the source is a subquery or join, run the same check on that query, because a join to another table can multiply rows (a fan-out) even when the base table has unique keys.
Duplicates on the insert side
The cardinality error is not the only symptom. Suppose a product is missing from the target and the source has it twice:
INSERT INTO inventory_updates (product_id, name, delta) VALUES
(4, 'screw', 200),
(4, 'screw', 5);Both rows of product 4 are evaluated against the target as it looked when the statement began, and neither finds a match. Both take the WHEN NOT MATCHED branch and try to insert. The second insert collides with the first on the primary key:
ERROR: duplicate key value violates unique constraint "inventory_pkey"
SQLSTATE: 23505If the target has no unique constraint on the key, there is no error at all. You get two rows for product 4, which is usually worse. Deduplicating the source protects you in both cases.
Fix 1: aggregate when the changes add up
When each source row represents an increment, such as stock deltas, combine them with GROUP BY. The merged result is the same as applying every row in sequence:
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 AND t.quantity + s.delta <= 0 THEN
DELETE
WHEN MATCHED THEN
UPDATE SET quantity = t.quantity + s.delta,
updated_at = now()
WHEN NOT MATCHED AND s.delta > 0 THEN
INSERT (product_id, name, quantity)
VALUES (s.product_id, s.name, s.delta);Two details matter here:
- Every column that is not part of the group key needs an aggregate.
max(name)is a way to pick one value when the names should all be equal. If they might genuinely differ, decide which one wins rather than relying onmax. - Conditions in the
WHENclauses see the aggregated row. The delete testt.quantity + s.delta <= 0uses the total change, which is what you want. Testing individual rows would give the wrong answer.
After the sample data runs through this statement (with the product 4 rows still in the staging table), inventory holds bolt 100, nut 85 (50 + 25 + 10), washer 40, and screw 205 (200 + 5).
Fix 2: keep only the latest row when the source holds states
Sometimes each source row is a complete new value, not an increment. Summing would be wrong. Instead you pick the row that should win, typically the most recent one. DISTINCT ON does this concisely in PostgreSQL:
CREATE TABLE prices (
product_id int PRIMARY KEY,
price numeric(10,2) NOT NULL
);
CREATE TABLE price_feed (
product_id int NOT NULL,
price numeric(10,2) NOT NULL,
received_at timestamptz NOT NULL
);
INSERT INTO prices (product_id, price) VALUES
(1, 9.99),
(2, 4.50);
INSERT INTO price_feed (product_id, price, received_at) VALUES
(2, 4.75, '2026-11-27 08:00+00'),
(2, 5.00, '2026-11-27 09:30+00'),
(3, 1.20, '2026-11-27 07:15+00');
MERGE INTO prices AS t
USING (
SELECT DISTINCT ON (product_id) product_id, price
FROM price_feed
ORDER BY product_id, received_at DESC
) AS s
ON t.product_id = s.product_id
WHEN MATCHED THEN
UPDATE SET price = s.price
WHEN NOT MATCHED THEN
INSERT (product_id, price)
VALUES (s.product_id, s.price);
SELECT * FROM prices ORDER BY product_id;The final query shows product 1 at 9.99 (untouched), product 2 at 5.00 (the 09:30 value), and product 3 at 1.20 (inserted).
DISTINCT ON keeps the first row for each key in the ORDER BY order, so the ordering decides the winner. If two rows can share the same received_at, add a final tie-breaker column such as a sequence number. Without one, the choice between tied rows is arbitrary and can change between runs.
A portable alternative is row_number():
SELECT product_id, price
FROM (
SELECT product_id, price,
row_number() OVER (PARTITION BY product_id
ORDER BY received_at DESC) AS rn
FROM price_feed
) ranked
WHERE rn = 1;This is longer, but it lets you also use rank values in other conditions, and it is the form most other SQL databases accept.
Choosing a strategy
| Source rows mean | Strategy | Example |
|---|---|---|
| Increments to add together | `GROUP BY` with `sum()` | Stock deltas |
| Full replacement values | `DISTINCT ON` or `row_number() = 1` with an ordering column | Latest price |
| Duplicates are copies of the same fact | `SELECT DISTINCT` or `DISTINCT ON` | Re-delivered messages |
| Duplicates should never happen | Do nothing and let the error fire | Keyed reference data |
The last row is a legitimate choice. If duplicates in the source signal a bug upstream, the cardinality error acts as a free data-quality check. Silent deduplication would hide the problem.
Edge cases to watch for
- Fan-out from joins. A source of the form
FROM orders o JOIN order_lines l ...produces one row per line. If the merge key is the order, you must aggregate first. - NULL keys.
NULL = NULLis not true, so a source row with a null key never matches. It goes toWHEN NOT MATCHED. With a primary key on the target the insert fails on the not-null rule. Filter such rows out with aWHERE product_id IS NOT NULLin the source subquery, or decide how to handle them. - Composite keys. Deduplicate on all the columns used in the
ONcondition, not only one of them. - Case and whitespace. If the join key is text,
'Nut'and'nut 'are different values to the join but may look like duplicates to a person. Normalize the key in the source subquery (for example withlower(btrim(...))) so the join and the deduplication agree. - Conditions can avoid the error. The error appears when a second source row would actually change an already-changed target row. If the clause conditions or a
DO NOTHINGaction mean the extra rows take no action, no error is raised. Do not rely on this. It makes the outcome depend on the data, and it is easy to break with a later edit.
Summary of behavior
- Two or more source rows matching one target row, with an
UPDATEorDELETEaction, raises error 21000 and rolls back the statement. - Two or more source rows with a missing key all take the insert branch, which causes a unique violation (23505) or silent duplicates when no constraint exists.
- Prepare the source so its join key is unique: aggregate for increments, pick a winner for states.
- Make any ordering deterministic with a tie-breaker.
Exercise
A staging table shipments(order_id int, carton_count int) can contain several rows per order, and the target orders_summary(order_id int PRIMARY KEY, cartons int) should hold the total number of cartons per order. Write a MERGE that updates existing orders by adding the new total and inserts missing ones, without raising the cardinality error.
Show answer
Aggregate the source first so there is one row per order: MERGE INTO orderssummary AS t USING ( SELECT orderid, sum(cartoncount) AS cartons FROM shipments WHERE orderid IS NOT NULL GROUP BY orderid ) AS s ON t.orderid = s.orderid WHEN MATCHED THEN UPDATE SET cartons = t.cartons + s.cartons WHEN NOT MATCHED THEN INSERT (orderid, cartons) VALUES (s.orderid, s.cartons); Each orderid now appears once in the source, so no target row can be matched twice, and the IS NOT NULL filter keeps unmatched null keys out of the insert branch.
Exercise
A source table sensor_readings(sensor_id int, reading numeric, taken_at timestamptz) holds many readings per sensor. The target sensor_latest(sensor_id int PRIMARY KEY, reading numeric) must hold only each sensor's most recent reading. Which technique do you use for the source subquery, and why is a tie-breaker worth adding?
Show answer
Use DISTINCT ON (sensorid) with ORDER BY sensorid, takenat DESC (or rownumber() OVER (PARTITION BY sensorid ORDER BY takenat DESC) filtered to 1). The readings are states, not increments, so summing would be wrong. If two readings for a sensor have the same taken_at, the winner is arbitrary and can differ between runs, so add a final ORDER BY column that is unique, such as a reading id, to make the result repeatable.