Sub topic 2
External IDs: identifying records from another system
This chapter assumes you can write basic SQL (INSERT, UPDATE, SELECT, primary keys) and that you know what a table constraint is. The Python example uses the standard library only. You don't need to know ON CONFLICT yet. A later chapter covers it.
Why matching needs an identifier
An upsert has to decide whether an incoming record already exists in your table. That decision is the match. Everything else in an upsert pipeline, such as idempotency, batching, and stale-data guards, depends on the match being right.
When your data is copied in from another system, such as a CRM, a billing tool, or a partner feed, you need something to match on. An external ID is the identifier that the other system uses for a record. In a CRM it might be C-1001. In a payment provider it might be cus_8f2a91. In a partner's product feed it might be a SKU.
The external ID is a good match key because the source system issues it and keeps it for the record's lifetime. It also doesn't depend on any attribute of the record that a person can edit.
Why not match on other fields
New pipeline authors often try to match on a field they can see, such as a name or an email address. These fields are poor keys because they change or repeat.
| Candidate match field | What goes wrong |
|---|---|
| Name | People change names. Different people share names. Spelling is corrected or reformatted. |
| Addresses change, are shared (`[email protected]`), or are missing. | |
| Row position in a file | Position changes whenever the source adds or removes rows. |
| Composite of several fields | A change to any one field makes the record look new. |
If you match on a field that changes, an edit in the source looks like a brand-new record. You insert it as a second row, and the old row stays behind. The result is duplicates that are hard to detect and harder to merge.
The next example shows this. A CRM renames customer C-1001 from "Ada Lovelace" to "Ada King". One table matches on name and the other matches on the external ID.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE by_name (id INTEGER PRIMARY KEY, name TEXT NOT NULL)")
conn.execute(
"CREATE TABLE by_external_id ("
"id INTEGER PRIMARY KEY, "
"source_system TEXT NOT NULL, "
"external_id TEXT NOT NULL, "
"name TEXT NOT NULL, "
"UNIQUE (source_system, external_id))"
)
day1 = ("crm", "C-1001", "Ada Lovelace")
day2 = ("crm", "C-1001", "Ada King") # same customer, renamed
for source_system, external_id, name in (day1, day2):
# Matching on name: the renamed record is not found, so it is inserted again.
found = conn.execute("SELECT id FROM by_name WHERE name = ?", (name,)).fetchone()
if found is None:
conn.execute("INSERT INTO by_name (name) VALUES (?)", (name,))
# Matching on the external ID: the second run updates the existing row.
conn.execute(
"INSERT INTO by_external_id (source_system, external_id, name) "
"VALUES (?, ?, ?) "
"ON CONFLICT (source_system, external_id) "
"DO UPDATE SET name = excluded.name",
(source_system, external_id, name),
)
print(conn.execute("SELECT COUNT(*) FROM by_name").fetchone()[0]) # 2
print(conn.execute("SELECT COUNT(*) FROM by_external_id").fetchone()[0]) # 1The name-based table ends with two rows for one customer. The external-ID table has one row with the current name.
Where external IDs come from
Most of the time you don't choose the external ID. You adopt the one the source system exposes. Look for these places:
- A field named
id,uuid,key,customer_number, orskuin the source's API response or export file. - A custom "external ID" field that the system provides for integrations. Salesforce, for example, lets you mark a custom field as an external ID so that you can address records by it.
- The primary key of the source database, if you are reading from it directly.
Some systems offer several identifiers. Prefer the one the source documents as stable and unique. Avoid display values, such as a friendly "account number" that support staff can edit.
What makes a good external ID
Before you build on an identifier, check that it has these properties:
- Unique within its source. No two records in the source share the value.
- Stable. The value does not change when the record's other fields change.
- Present. Every record has one. A null external ID can never be matched.
- Never reused. If the source deletes a record, it doesn't hand the same ID to a different record later. Some systems recycle numeric IDs or SKUs, so check the documentation.
You can check the first and third properties on a sample file before you design the table. Load the file into a staging table and run a query like this:
SELECT external_id, COUNT(*) AS copies
FROM staging_customers
GROUP BY external_id
HAVING COUNT(*) > 1
ORDER BY copies DESC;If this returns rows, the source either has real duplicates or the field is not the unique identifier you assumed. Resolve that first. You can't make an upsert reliable on a key that isn't unique. To find missing values, run SELECT COUNT(*) FROM staging_customers WHERE external_id IS NULL.
Scope the ID by its source system
An external ID is only unique inside the system that issued it. The CRM's 1001 and the billing system's 1001 are unrelated records. If you load both into one table and store only 1001, they collide.
The fix is to store the name of the source system next to the ID, and treat the pair as the identity. The pair (source_system, external_id) is what the sample table in this tutorial uses:
CREATE TABLE customers (
id bigserial PRIMARY KEY,
source_system text NOT NULL,
external_id text NOT NULL,
name text NOT NULL,
email text,
UNIQUE (source_system, external_id)
);Here source_system holds values such as 'crm' or 'billing'. The table also has its own primary key, id. The next chapter explains why you keep both, and the one after covers the UNIQUE constraint in detail. For now, note that the external ID is a column like any other. Your table doesn't use it as the primary key.
If you only ever load from one source, you can leave out source_system. Adding it later means changing a constraint on a populated table, so many teams include it from the start.
Choose a data type deliberately
Store external IDs as text unless you have a strong reason not to. Even when the source's IDs look numeric, treat them as labels, not numbers.
- Leading zeros matter.
00123and123are different IDs, but they are equal as integers. - Sources change format. A numeric ID may later become
C-1001or a UUID. - You never do arithmetic on an ID.
- Very large numeric IDs can exceed the integer range of your database or of languages that parse JSON numbers as floating point. A 19-digit ID can silently lose precision this way.
In Python, read IDs from CSV files as strings. Don't let a library infer a numeric type for the column.
Data flow
The diagram shows where the external ID sits in a typical load. The source system issues the ID, and your table stores it next to your own key.
In SQL, the upsert statement performs the lookup and the choice between update and insert in one step. This chapter only establishes what the lookup key is.
Common mistakes
- Using the source's display fields as the ID. Names, emails, and titles change.
- Dropping the source system. Two systems with the same ID value then overwrite each other's rows.
- Storing IDs as integers. Leading zeros are lost and large values can lose precision.
- Assuming every record has an ID. Rows without one need a policy: reject them, route them to an error table, or generate a different key. Don't insert them with a null external ID.
- Ignoring formatting differences.
c-1001andC-1001(with a trailing space) look the same to a person and are different strings to the database. Normalizing values before matching is a separate topic that a later chapter covers.
Summary
An external ID is the identifier a source system gives a record. It is the right match key for an upsert because the source controls it and it stays the same when the record's other fields change. Pick a field that is unique, stable, present, and not reused. Store it as text, and pair it with the name of the source system. Then the rest of the pipeline can rely on the match.
Exercise
A billing system exports invoices with a column invoice_number (for example INV-0042, which finance staff can edit to fix typos) and a column invoice_uuid (assigned by the system and never shown to users). You are building an upsert from this export. Which column should be the external ID, and why? Also, what second column should you store next to it if you later add a second system that also exports invoices?
Show answer
Use invoice_uuid. The system assigns it, so it stays stable and unique when the invoice's other fields are edited. invoice_number can be edited, so an edit would look like a new record and create a duplicate row. Next to the external ID, store a source_system column (for example 'billing') so that IDs from the second system can't collide with it. The identity of a row is then the pair (source_system, external_id).
Exercise
A CSV file has the external ID 007342 in its first column. A script loads it with a library that guesses column types, and the value reaches the database as 7342. Name two problems this can cause for an upsert, and give the fix.
Show answer
First, 7342 doesn't match an existing row stored as 007342, so the load inserts a duplicate. Second, 7342 might match a different record whose real ID is 7342, so the upsert overwrites the wrong row. The fix is to read the column as text (for example, tell the CSV reader to treat the column as a string) and store the ID in a text column.