Sub topic 8
Normalizing External ID Values Before Matching
This chapter assumes you can write a PostgreSQL INSERT ... ON CONFLICT upsert and know that the external ID column has a unique constraint. Both come from earlier chapters.
Why matching can fail
A unique constraint compares values exactly. To the database, C-1001, c-1001 and C-1001 (with a trailing space) are three different values. If one source sends all three spellings over time, your upsert inserts three rows. The constraint does not complain, because none of them conflict.
The fix is to normalize the ID before it reaches the database. Normalizing means converting every accepted spelling of an ID to one canonical form.
Choosing the rules
Decide the rules from what the source system actually guarantees. Common rules are:
- Trim leading and trailing whitespace, including non-breaking spaces copied from spreadsheets.
- Apply Unicode normalization, so that look-alike characters such as full-width digits become plain ones.
- Change case, but only if the source treats IDs as case-insensitive.
- Reject empty values instead of storing them.
Some changes are unsafe. Do not remove leading zeros unless the source does too. In a system where 007 and 7 are different records, stripping zeros merges two customers into one. Do not lowercase IDs from a system where aB3 and Ab3 are distinct. Normalization must never make two different source records look identical.
A worked example
This Python script normalizes IDs and then upserts. It uses SQLite, so it runs without a server.
import sqlite3
import unicodedata
def normalize_external_id(value):
text = unicodedata.normalize("NFKC", value).strip().upper()
if not text:
raise ValueError("external ID is empty")
return text
conn = sqlite3.connect(":memory:")
conn.execute(
"CREATE TABLE customers ("
"id INTEGER PRIMARY KEY, "
"external_id TEXT NOT NULL UNIQUE, "
"name TEXT NOT NULL)"
)
sql = (
"INSERT INTO customers (external_id, name) VALUES (?, ?) "
"ON CONFLICT(external_id) DO UPDATE SET name = excluded.name"
)
raw_rows = [
("c-1001", "Ada Lovelace"),
(" C-1001 ", "Ada Lovelace"),
("C-1001\u00a0", "Ada King"),
]
for raw_id, name in raw_rows:
conn.execute(sql, (normalize_external_id(raw_id), name))
print(conn.execute("SELECT COUNT(*) FROM customers").fetchone()[0]) # 1
print(conn.execute("SELECT external_id, name FROM customers").fetchone())
# ('C-1001', 'Ada King')All three spellings collapse to C-1001, so the table holds one row. Without the function, it would hold three.
Enforcing the rule in the database
Application code is one place to normalize, but other writers, such as scripts and manual fixes, may skip it. In PostgreSQL you can make the database reject IDs that are not already in canonical form:
ALTER TABLE customers
ADD CONSTRAINT external_id_is_canonical
CHECK (external_id = upper(btrim(external_id)) AND external_id <> '');A write that bypasses your function now fails loudly instead of silently creating a duplicate. Another option is a unique index on an expression such as upper(btrim(external_id)). The upsert's ON CONFLICT target must then repeat the same expression. The check constraint is simpler, because the existing UNIQUE (source_system, external_id) keeps working unchanged.
Where to apply it
Apply the same function everywhere an ID is compared: the upsert, lookups, and any join against data from the source. If the upsert normalizes but a lookup does not, SELECT ... WHERE external_id = 'c-1001' finds nothing even though the row exists. Keep the function in one shared module so the rules cannot drift apart.
Exercise
A source system treats IDs as case-sensitive, so AB12 and ab12 are different customers. Your normalizer calls .upper(). What goes wrong, and what should you change?
Show answer
The normalizer maps two different customers to AB12, so the upsert overwrites one customer's data with the other's. Remove the case change and keep only safe rules, such as trimming whitespace and Unicode normalization. Then fix any rows that were already merged.