Sub topic 10
Handling duplicate external IDs inside one batch
This chapter assumes you can write a PostgreSQL INSERT ... ON CONFLICT DO UPDATE keyed on (source_system, external_id), and that you have read the earlier chapters on the unique constraint and on normalizing external IDs.
The problem
A batch upsert sends many rows in one statement. The unique constraint protects you from duplicates already stored in the table. It does not help when the same external ID appears twice in the batch itself.
Suppose a CRM export contains C-1001 twice, once from an early edit and once from a later one. PostgreSQL rejects the statement:
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 statement is all-or-nothing, so one duplicate fails the whole batch. Even if the database accepted it, the database would have to pick a winner between the two rows, and you should make that choice yourself.
Decide which row wins
Before writing code, pick a rule. Two common ones:
| Rule | Use it when |
|---|---|
| Latest `source_updated_at` wins | The source gives a reliable modification time |
| Last row in the file wins | The source has no timestamp but writes rows in order |
If neither rule fits, treat the duplicate as a data error and report it. Do not guess.
Normalize the external ID first. "c-1001 " and "C-1001" are the same record, and you only see that after trimming and case-folding. Deduplicating before normalizing leaves duplicates that still collide in the database.
Deduplicate in the application
This script normalizes each ID and keeps one row per ID. The row with the newest timestamp wins. If timestamps tie, the later row wins.
from datetime import datetime
rows = [
{"external_id": "C-1001 ", "name": "Ada Lovelace", "updated": "2026-11-29T09:00:00+00:00"},
{"external_id": "c-1002", "name": "Grace Hopper", "updated": "2026-11-29T10:00:00+00:00"},
{"external_id": "c-1001", "name": "Ada King", "updated": "2026-11-30T12:00:00+00:00"},
]
def normalize(external_id: str) -> str:
return external_id.strip().upper()
def dedupe(batch):
latest = {}
for row in batch:
key = normalize(row["external_id"])
ts = datetime.fromisoformat(row["updated"])
current = latest.get(key)
if current is None or ts >= current[0]:
latest[key] = (ts, {**row, "external_id": key})
return [item[1] for item in latest.values()]
result = dedupe(rows)
print(len(rows), "->", len(result))
for row in result:
print(row["external_id"], row["name"])The output shows three input rows reduced to two. C-1001 keeps the name "Ada King" because its timestamp is newer, even though it appeared later in the list for a different reason. Use >= so the later row wins a tie.
Deduplicate in SQL
If you load rows into a staging table first, let PostgreSQL pick the winner with DISTINCT ON. This example assumes a customers_staging table with the same columns as customers, with IDs already normalized.
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 customers_staging
ORDER BY source_system, external_id, source_updated_at DESC NULLS LAST
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;DISTINCT ON keeps the first row for each key in the ORDER BY. Sorting by source_updated_at DESC makes that first row the newest. The WHERE clause is the stale guard from the previous chapter, so the batch also cannot overwrite newer data already in the table.
Common mistakes
- Deduplicating on the raw ID instead of the normalized ID.
- Sorting ascending in
DISTINCT ON, which keeps the oldest row. - Splitting the batch into single-row statements to avoid the error. This hides the duplicate and lets the last row silently win, whatever its timestamp.
Exercise
A batch has two rows with sourcesystem 'crm' and externalid 'C-2001'. The first has sourceupdatedat 2026-11-30 and the second has 2026-11-28. The loader uses DISTINCT ON with ORDER BY sourcesystem, externalid, sourceupdatedat ASC. Which row is loaded, and what should change?
Show answer
The 2026-11-28 row is loaded, because ascending order puts the oldest row first and DISTINCT ON keeps the first one. Change the order to sourceupdatedat DESC so the newest row wins.