Sub topic 3
Upserting Many Records with External IDs
Assume you know basic SQL, primary keys, constraints, and a scripting language. A batch upsert applies the same insert-or-update operation to many records. Each record must contain a normalized external ID, such as C-1001, and that ID must be unique in the destination table.
Upserting a Batch
In PostgreSQL, send multiple rows to one INSERT ... ON CONFLICT statement. The unique constraint identifies an existing record.
INSERT INTO customers (source_system, external_id, name, email)
VALUES
('crm', 'C-1001', 'Ada Lovelace', '[email protected]'),
('crm', 'C-1002', 'Grace Hopper', '[email protected]')
ON CONFLICT (source_system, external_id)
DO UPDATE SET
name = EXCLUDED.name,
email = EXCLUDED.email;EXCLUDED means the incoming row. The statement updates only the columns that the source owns.
flowchart TD
A[Read source batch] --> B[Normalize external IDs]
B --> C[Remove duplicates]
C --> D[Batch upsert]
D --> E[Check counts and rerun]Duplicate IDs and Stale Data
PostgreSQL rejects a batch when multiple incoming rows try to update the same target row in one statement. Deduplicate the batch before sending it. Keep one row per external ID, usually the row with the newest source timestamp.
A stale-data guard prevents an older message from replacing newer data:
ON CONFLICT (source_system, external_id)
DO UPDATE SET
name = EXCLUDED.name,
source_updated_at = EXCLUDED.source_updated_at
WHERE customers.source_updated_at IS NULL
OR customers.source_updated_at < EXCLUDED.source_updated_at;The source timestamp must use a consistent time zone and meaning.
APIs and Concurrent Writers
An API can expose the same operation through a request addressed by an external ID:
PATCH /customers/external/crm/C-1001
Content-Type: application/json
{"name":"Ada Lovelace","email":"[email protected]"}The API commonly returns 201 Created for an insert and 200 OK or 204 No Content for an update. Check the API's documented contract rather than inferring the result from the request method.
Concurrent writers can race if they first run SELECT and then choose INSERT or UPDATE. A database unique constraint and atomic upsert let the database resolve that race. Handle any remaining transaction or serialization errors with suitable retry logic.
Verification
Record the input count, accepted count, rejected count, and affected rows. Rerun the identical batch. The row count should stay unchanged, and values should remain correct. Also test a changed source value and an older source timestamp.
Exercise
A batch contains two rows for C-1001, with source timestamps 10:00 and 11:00. Which row should normally be upserted?
Show answer
Keep the 11:00 row, assuming both timestamps describe the same source field and use the same time zone.