Sub topic 8
Normalizing External ID Values Before Matching
This chapter assumes you know basic SQL (INSERT, UPDATE, SELECT, primary keys), have read the earlier chapters on external IDs and unique constraints, and can read short Python scripts. It covers what goes wrong when the same external ID arrives in slightly different forms, and how to fix it before the upsert runs.
Why normalization matters
An upsert matches on equality. The database compares the incoming external_id with stored values byte by byte (or by the column's collation) and decides: same value means update, different value means insert.
That is a problem when the source system is not consistent about how it writes an ID. Consider these values:
C-1001c-1001C-1001(leading space)C-1001\n(trailing newline from a CSV export)C‑1001(a non-breaking hyphen instead of a plain hyphen)
A person would call all of these the same customer. A unique constraint on (source_system, external_id) treats them as five different keys. Each one passes the constraint and inserts a new row. The result is silent duplicates: no error, no warning, and the row count grows on every load that uses a new spelling.
Normalization means converting an external ID to one canonical form before it reaches the upsert. After that, equal records produce equal keys.
Decide the canonical form first
Normalization rules belong to the source system, not to you. Before you write code, find out how the source defines its IDs. Questions to answer:
- Is the ID case-sensitive? Some systems treat
abcandABCas different records. Others do not. - Does the ID have meaningful leading zeros?
00123and123may be different records, or the same. - Can the ID contain whitespace or punctuation that is only formatting?
- What type is it in the source? A numeric ID exported to a spreadsheet may come back as
1001.0or1.001E+3.
Write the answers down as a rule. A rule you cannot state, such as "strip whitespace, uppercase, keep leading zeros", is a rule you cannot test.
Be conservative. Over-normalizing is also a bug. If the source treats AB and ab as two customers and you uppercase both, you merge two real records into one, and the upsert then overwrites one customer's data with the other's. Normalize only differences that the source itself considers meaningless.
Common problems and fixes
| Problem | Example | Typical fix |
|---|---|---|
| Surrounding whitespace | `" C-1001 "` | Strip leading and trailing whitespace |
| Inconsistent case | `c-1001` | Uppercase or lowercase, if the source is case-insensitive |
| Numeric formatting | `1001.0` from a spreadsheet | Parse as a number, then convert to an integer string |
| Lost leading zeros | `123` instead of `00123` | Read the column as text, never as a number |
| Unicode look-alikes | non-breaking hyphen or space | Apply Unicode normalization, then replace known variants |
| Empty or placeholder values | `""`, `"NULL"`, `"N/A"` | Reject the record or route it to an error list |
The last row matters. An empty string is a valid text value, so a unique constraint accepts one row with external_id = '', and every later record with a blank ID collides with it. The upsert would then merge unrelated records into that one row. Treat a missing ID as an error, not as a key.
A normalization function
Keep the rules in one function and call it from every load path. If two scripts normalize differently, you get the same duplicate problem between them.
import re
import unicodedata
PLACEHOLDERS = {"", "NULL", "N/A", "NONE"}
def normalize_external_id(raw):
"""Return the canonical form of an external ID.
Rules for this source: IDs are case-insensitive, whitespace and
hyphen style are formatting only, leading zeros are kept.
Raises ValueError for missing or placeholder IDs.
"""
if raw is None:
raise ValueError("missing external ID")
# Fold compatibility characters, such as a non-breaking space
# or a full-width digit, into their plain equivalents.
text = unicodedata.normalize("NFKC", str(raw))
# Replace the Unicode hyphen and dash variants with a plain hyphen.
text = re.sub(r"[\u2010\u2011\u2012\u2013\u2014\u2212]", "-", text)
# Remove surrounding whitespace, then apply the case rule.
text = text.strip().upper()
if text in PLACEHOLDERS:
raise ValueError(f"placeholder external ID: {raw!r}")
return text
if __name__ == "__main__":
samples = ["C-1001", "c-1001", " C-1001 ", "C-1001\n", "C\u20111001"]
print({normalize_external_id(s) for s in samples}) # {'C-1001'}All five spellings from the start of this chapter collapse to one value. NFKC is a Unicode normal form that folds compatibility characters into plain ones. For example, it turns a non-breaking space into a regular space, so strip() can then remove it. The explicit hyphen replacement is separate because NFKC does not convert every dash to a hyphen-minus. The U+2011 non-breaking hyphen does fold to U+2010, which is still not an ASCII hyphen, so the regex covers it.
Use the function in the upsert path
Apply normalization in the code that builds the query parameters. The SQL stays the same as in the earlier chapter.
import sqlite3
from normalize import normalize_external_id # the function above, saved as normalize.py
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\n", "Ada King")]
clean_rows = []
rejected = []
for raw_id, name in raw_rows:
try:
clean_rows.append((normalize_external_id(raw_id), name))
except ValueError as err:
rejected.append((raw_id, str(err)))
conn.executemany(sql, clean_rows)
print(conn.execute("SELECT external_id, name FROM customers").fetchall())
# [('C-1001', 'Ada King')]
print(rejected) # []Without the normalize call, this batch would insert two rows. With it, the second record updates the first. Keep a rejected list and report it at the end of the load, so a bad ID is visible instead of silently dropped.
Note that both rows in this batch now share one normalized ID. That is a duplicate within a single batch, which the next chapters on batches cover. In SQLite the second statement simply wins because rows run one at a time. PostgreSQL behaves differently when both rows are in one multi-row INSERT, and it raises an error. Normalize first, then deduplicate the batch before you send it.
Normalizing in the database
Application code is the right place for most rules, because you can unit test it and it runs before any data touches the table. The database can still act as a safety net. PostgreSQL lets you add a check constraint that rejects IDs that are not in canonical form:
ALTER TABLE customers
ADD CONSTRAINT customers_external_id_canonical
CHECK (
external_id = upper(btrim(external_id))
AND external_id <> ''
);With this constraint, a load path that forgets to normalize fails loudly with a constraint violation. That is better than creating a duplicate quietly. Before you add it to an existing table, check for rows that already violate it, because ALTER TABLE ... ADD CONSTRAINT fails if any do:
SELECT id, external_id
FROM customers
WHERE external_id <> upper(btrim(external_id))
OR external_id = '';Another option is a unique index on an expression, for example CREATE UNIQUE INDEX ON customers (source_system, upper(external_id)). It makes the database treat case variants as the same key. However, ON CONFLICT must then name the same expression, and the stored value keeps its original case. The check constraint approach keeps the stored data clean, which makes joins and exports simpler.
Do not change IDs after the fact without a plan
If you add normalization to a pipeline that has already loaded data, old rows may be stored in non-canonical form. New loads will then not match them, and you create duplicates the first time you run the new code. Before deploying:
- Run a query that finds stored IDs that change when normalized.
- Find pairs of rows that collapse to the same canonical ID. These are existing duplicates that you must merge by hand or by script, including any foreign keys that point at them.
- Update the remaining rows to the canonical form.
- Only then add the check constraint and deploy the new load code.
Also keep the raw value if it has audit value. A separate column such as external_id_raw lets you trace a record back to exactly what the source sent.
Summary of the working model
- An upsert is only as reliable as the equality it matches on.
- Define the canonical form from the source system's own rules, and normalize no more than that.
- Reject empty and placeholder IDs instead of storing them.
- Put the rules in one function used by every load path.
- Let a check constraint catch any path that skips it.
- Clean existing data before you turn the new rules on.
Exercise
A batch contains the external IDs "00457", "457", and " 00457 ". The source system documents that IDs are strings and that leading zeros are significant. Which of these should normalize to the same value, and what would go wrong if your loader read the column as an integer?
Show answer
Only "00457" and " 00457 " are the same ID; stripping whitespace makes them both "00457". "457" is a different ID because leading zeros are significant. If the loader parsed the column as an integer, all three would become 457, so the upsert would merge records that the source treats as distinct, and one customer's data would overwrite another's. Read the ID column as text.
Exercise
Your table has UNIQUE (sourcesystem, externalid) and no normalization. A load runs on Monday with the ID "A-9" and on Tuesday with "a-9", for the same customer. How many rows exist after Tuesday, and which two changes would prevent the problem?
Show answer
Two rows exist, because the constraint compares the strings "A-9" and "a-9" as different values, so Tuesday's upsert inserts instead of updating. Prevent it by normalizing the ID (for example, uppercasing it) in the load code before the upsert, and by adding a CHECK constraint such as externalid = upper(btrim(externalid)) so any path that skips normalization fails instead of creating a duplicate. Before adding the constraint, merge the existing duplicate rows.