Sub topic 10
Handling duplicate external IDs inside one batch
This chapter assumes you can write a PostgreSQL INSERT ... ON CONFLICT DO UPDATE statement. It also assumes you have a table with a unique constraint on (source_system, external_id), as in the earlier chapters, and that you can read basic Python. The examples use the customers table from those chapters, including the source_updated_at column.
Why duplicates inside one batch are a separate problem
Earlier chapters showed that an upsert is safe to repeat. Run the same load twice and the second run updates rows instead of adding new ones. That works because each statement meets a given external ID at most once.
A batch can break that assumption. A source system may export a customer twice. An event stream may contain three edits to the same record. A file may be the concatenation of two exports. The batch then holds several rows that all match the same row in the table.
PostgreSQL rejects this case when one statement proposes two rows with the same conflict key and the conflict action is DO UPDATE:
ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time
HINT: Ensure that no rows proposed for insertion within the same command have duplicate constrained values.The database refuses because the result would depend on row order. It does not know which of the two proposed rows should win, so it fails the whole statement and writes nothing from it.
Reproducing the failure
Suppose a CRM export contains the same customer twice, with a rename in between:
INSERT INTO customers (source_system, external_id, name, email, source_updated_at)
VALUES
('crm', 'C-1001', 'Ada Lovelace', '[email protected]', '2026-11-30T09:00:00Z'),
('crm', 'C-1001', 'Ada King', '[email protected]', '2026-11-30T12:00:00Z')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name,
email = EXCLUDED.email,
source_updated_at = EXCLUDED.source_updated_at;This fails with the error above, even if the table is empty. The conflict is between the two proposed rows, not with stored data. The check applies to the statement as a whole, so the error does not depend on what the table already contains.
Deciding what "duplicate" should mean
Before you write code, decide which row should survive. The table lists the common policies.
| Policy | Rule | Use when |
|---|---|---|
| Newest timestamp wins | Keep the row with the greatest `source_updated_at` | The source supplies a reliable modification time |
| Last row wins | Keep the row that appears latest in the batch | The batch is an ordered log of changes |
| Merge | Combine fields from several rows | Each duplicate carries different columns |
| Reject | Fail the batch and report the duplicates | Duplicates mean the export is broken |
"Newest timestamp wins" is the safest default. It matches the stale guard from the previous chapter: the batch is reduced to the same row the guard would have kept if the rows had arrived one at a time.
Row order in a file is a weak signal. Exports are often sorted by name or ID, not by time. Use order only when you know the source preserves it.
The "merge" policy needs care. If row A has an email and a blank name, and row B has a name and no email, a merge produces a record that never existed in the source. Do this only when you understand the source's semantics for missing fields.
Normalize first, then deduplicate
Deduplication compares keys, so the keys must be in their canonical form before you compare them. If one row says C-1001 and another says c-1001 with a trailing space, the unique constraint treats them as different values. Neither the constraint nor the error would catch the problem. You would silently end up with two rows for one customer.
The earlier chapter on normalization defined the rules for your source, such as trimming whitespace and fixing case. Apply exactly the same function here, and apply it before grouping. The order matters:
- Normalize the external ID of every incoming row.
- Group rows by
(source_system, normalized_external_id). - Pick one survivor per group.
- Send the survivors to the database.
Deduplicating in application code
When the batch is already in memory, a dictionary keyed on the match key does the job. This program is complete and runs as shown. It uses the "newest timestamp wins" policy and breaks ties in favor of the later row.
from datetime import datetime
def normalize_id(value):
return value.strip().upper()
def dedupe(records):
"""Keep one record per (source_system, external_id): the newest one."""
survivors = {}
discarded = []
for rec in records:
key = (rec["source_system"], normalize_id(rec["external_id"]))
rec = {**rec, "external_id": key[1]}
current = survivors.get(key)
if current is None:
survivors[key] = rec
elif rec["source_updated_at"] >= current["source_updated_at"]:
discarded.append(current)
survivors[key] = rec
else:
discarded.append(rec)
return list(survivors.values()), discarded
def ts(text):
return datetime.fromisoformat(text)
batch = [
{"source_system": "crm", "external_id": "C-1001", "name": "Ada Lovelace",
"source_updated_at": ts("2026-11-30T09:00:00+00:00")},
{"source_system": "crm", "external_id": " c-1001", "name": "Ada King",
"source_updated_at": ts("2026-11-30T12:00:00+00:00")},
{"source_system": "crm", "external_id": "C-1002", "name": "Grace Hopper",
"source_updated_at": ts("2026-11-30T10:00:00+00:00")},
]
kept, dropped = dedupe(batch)
for rec in kept:
print("keep", rec["external_id"], rec["name"])
for rec in dropped:
print("drop", rec["external_id"], rec["name"])The output is:
keep C-1001 Ada King
keep C-1002 Grace Hopper
drop C-1001 Ada LovelaceNote that " c-1001" and "C-1001" were recognized as the same record only because normalization ran first. The program also keeps the discarded rows. Counting them and logging them is how you notice that a source has started to send more duplicates than usual.
Deduplicating inside the SQL statement
If the rows are already in the database, for example in a staging table, you can remove duplicates in the SELECT that feeds the insert. PostgreSQL's DISTINCT ON keeps the first row of each group according to the ORDER BY:
INSERT INTO customers (source_system, external_id, name, email, source_updated_at)
SELECT DISTINCT ON (source_system, external_id)
source_system, external_id, name, email, source_updated_at
FROM (VALUES
('crm', 'C-1001', 'Ada Lovelace', '[email protected]', '2026-11-30T09:00:00Z'::timestamptz),
('crm', 'C-1001', 'Ada King', '[email protected]', '2026-11-30T12:00:00Z'::timestamptz),
('crm', 'C-1002', 'Grace Hopper', '[email protected]', '2026-11-30T10:00:00Z'::timestamptz)
) AS incoming(source_system, external_id, name, email, source_updated_at)
ORDER BY source_system, external_id, source_updated_at DESC
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name,
email = EXCLUDED.email,
source_updated_at = EXCLUDED.source_updated_at
WHERE customers.source_updated_at IS NULL
OR customers.source_updated_at < EXCLUDED.source_updated_at;The ORDER BY has two jobs. Its leading columns must match the DISTINCT ON columns, and the trailing source_updated_at DESC puts the newest row first in each group, so that row survives. The WHERE clause at the end is the stale guard from the previous chapter. It protects rows already stored, while DISTINCT ON protects against duplicates inside the batch. You need both.
Why not just use DO NOTHING?
ON CONFLICT DO NOTHING does not raise the "second time" error. It skips every proposed row that conflicts, whether the conflict is with a stored row or with an earlier row in the same statement. That makes the statement run, but the effect is that the first row in the batch wins and everything else is dropped. Existing rows are never updated.
This is rarely what a synchronization job wants. The first row in a batch is often the oldest. Use DO NOTHING only for loads that should insert new records and never change existing ones.
Duplicates across batches are a different case
Two rows with the same external ID in separate statements are not a problem. The first statement inserts the row. The second finds a conflict with the stored row and updates it, subject to your update rules and stale guard. This is the normal idempotent behavior from earlier chapters.
The error in this chapter only occurs when both rows are proposed by one statement. That has a practical consequence for batch size. A single large statement is faster, but it exposes you to this error. Many single-row statements avoid it, but they pay for a round trip per row and the last row wins by default. Deduplicating first lets you use large statements safely.
Common mistakes
- Deduplicating before normalizing. Variants of the same ID survive as separate keys. Normalize first.
- Deduplicating on
external_idalone. The unique constraint is on(source_system, external_id). Two systems can reuse the same ID for different records. Group on the same columns as the constraint. - Choosing the survivor by file order. Sorted exports put older rows after newer ones. Compare timestamps when the source provides them.
- Dropping duplicates silently. If a source suddenly sends 30% duplicates, something changed upstream. Log the count.
- Retrying on the error. The failure is deterministic. Retrying the same batch produces the same error. Fix the input.
Exercise
A nightly job loads 10,000 customer rows with one multi-row INSERT ... ON CONFLICT (sourcesystem, externalid) DO UPDATE statement. One night it fails with "ON CONFLICT DO UPDATE command cannot affect row a second time", although the customers table is empty. What is the cause, and how do you fix the load so that the newest row per customer is kept?
Show answer
The batch contains two or more rows with the same (sourcesystem, externalid). The statement cannot choose between them, so PostgreSQL rejects it. This happens even on an empty table because the conflict is between rows proposed by the same statement. Fix it by normalizing the external IDs and then keeping one row per key before the insert. In SQL, use SELECT DISTINCT ON (sourcesystem, externalid) ... ORDER BY sourcesystem, externalid, sourceupdatedat DESC as the source of the INSERT, with a tiebreaker column if timestamps can be equal. Alternatively, deduplicate in application code with a dictionary keyed on the normalized key. Keep the stale-update WHERE clause so stored newer data is still protected.