Sub topic 1
Upserting Records with External IDs
Prerequisites
This chapter assumes basic SQL, including INSERT, primary keys, and constraints. You should also understand that two systems can store the same customer with different identifiers.
What an Upsert Does
An upsert combines an insert and an update. It inserts a row when no matching row exists. It updates the existing row when a match exists.
Without an upsert, application code often follows this sequence:
- Search for a matching row.
- Insert if the search finds nothing.
- Update if the search finds a row.
That sequence can be vulnerable to race conditions. Two workers might search at the same time, both find nothing, and both try to insert. An upsert lets the database perform the match and write as one operation.
External IDs
An external ID is an identifier assigned by another system. For example, a CRM might identify a customer as C-1001. Your database should use that value to find the customer during synchronization.
Do not match only on a name or email address unless the source system guarantees that value is stable and unique. Names can change, and email addresses can be shared or corrected.
An external ID is usually unique only within its source system. Therefore, store the source as part of the identity when multiple systems send data.
Internal and External Keys
Keep your own primary key for relationships inside your database. Store the external ID separately for synchronization.
CREATE TABLE customers (
id bigserial PRIMARY KEY,
source_system text NOT NULL,
external_id text NOT NULL,
name text NOT NULL,
UNIQUE (source_system, external_id)
);The id value is stable for local foreign keys. The pair (source_system, external_id) identifies the source record.
Enforcing Uniqueness
A unique constraint prevents two rows from having the same key. It makes the upsert match reliable and gives concurrent writers a database-enforced boundary.
The constraint must match the identity rule. If C-1001 from crm and C-1001 from billing are different records, use the pair as shown above. Normalize identifiers before matching when the source permits equivalent forms, such as surrounding whitespace or inconsistent case.
Exercise
Why should a synchronized table keep both an internal primary key and an external ID?
Show answer
The internal key supports local relationships, while the external ID lets the load find the corresponding record in the source system.