Sub topic 4
Enforcing Uniqueness So the Match Is Reliable
An upsert is only as trustworthy as the match it makes. If two rows can carry the same external ID, "find the record with this ID" has no single answer. This chapter covers how a unique constraint makes the match reliable, how to scope it correctly, and what goes wrong when it is missing or too narrow.
This chapter assumes you know basic SQL (INSERT, UPDATE, SELECT), what a primary key is, and that records are often copied between separate systems. Examples use PostgreSQL unless stated otherwise.
Why the match needs a guarantee
An upsert asks the database one question: does a row with this external ID already exist? If it does, update it. If not, insert one.
That question is only safe when the answer is zero or one row. Consider what each outcome means:
- Zero rows: insert a new record.
- One row: update that record.
- Two or more rows: the database cannot know which to update, and your data already has a duplicate.
Application code can try to enforce this by running a SELECT first and inserting only when nothing comes back. That check is not a guarantee. Two processes can both see "no row" and both insert. A unique constraint moves the guarantee into the database, which is the only place that sees every writer.
What a unique constraint does
A unique constraint tells the database that no two rows may hold the same value in a column or combination of columns. Every INSERT and UPDATE is checked against it. A violating write fails with an error, and the database backs the constraint with a unique index so the check is fast.
That index is also what makes ON CONFLICT possible. The clause needs a constraint or unique index to name as the conflict target. Without one, PostgreSQL rejects the statement.
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)
);This table has two separate identities:
idis the internal primary key. Your own tables reference it, and it never changes.(source_system, external_id)is the match key. It identifies the record in the outside world.
Scope the constraint by source system
The constraint above covers two columns, not one. IDs are only unique inside the system that issued them. A CRM may use C-1001 for Ada Lovelace, while a billing system uses C-1001 for a different customer.
If you made external_id unique on its own, the second system's record would either be rejected or, worse, overwrite the first system's record during an upsert.
| Constraint | Effect when two systems both send `C-1001` |
|---|---|
| `UNIQUE (external_id)` | The second load fails, or an upsert overwrites the other system's customer. |
| `UNIQUE (source_system, external_id)` | Both rows are stored, each matched only by its own system. |
Choose the scope that matches how the IDs are issued. If you load from only one system and always will, a single-column constraint is acceptable. Adding source_system early costs little, and changing a key later means migrating data.
NOT NULL matters
Unique constraints have an edge case with NULL. In PostgreSQL, NULL is treated as "unknown", so two NULL values are not considered equal. A unique constraint therefore allows many rows with a NULL in the constrained column.
For an external ID, that would let duplicates slip in as rows that can never be matched. Declare the match columns NOT NULL, as the table above does. A record with no external ID cannot be upserted, so rejecting it at insert time is the correct outcome.
PostgreSQL 15 and later also offers UNIQUE NULLS NOT DISTINCT, which treats NULL values as equal. For match keys, NOT NULL is simpler and states the intent more clearly.
Adding the constraint to an existing table
Often the table already exists and holds data. Adding the constraint can fail if duplicates are already there.
ALTER TABLE customers
ADD CONSTRAINT customers_source_external_key
UNIQUE (source_system, external_id);If this raises a duplicate key error, find the offending rows first:
SELECT source_system, external_id, count(*)
FROM customers
GROUP BY source_system, external_id
HAVING count(*) > 1;Decide for each group which row survives, merge or delete the others, and update any rows that reference the removed id values. Only then add the constraint. Skipping the cleanup and hoping is not an option, because the database refuses to create the constraint while violations exist.
On a large, busy table, a plain ADD CONSTRAINT locks writes while it builds the index. A common approach is to build the index first without blocking writers, then attach it:
CREATE UNIQUE INDEX CONCURRENTLY customers_source_external_idx
ON customers (source_system, external_id);
ALTER TABLE customers
ADD CONSTRAINT customers_source_external_key
UNIQUE USING INDEX customers_source_external_idx;CREATE INDEX CONCURRENTLY cannot run inside a transaction block. If it fails partway, it leaves an invalid index that you must drop before retrying.
How the constraint drives the upsert
With the constraint in place, the upsert names it as the conflict target:
INSERT INTO customers (source_system, external_id, name, email)
VALUES ('crm', 'C-1001', 'Ada Lovelace', '[email protected]')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name, email = EXCLUDED.email
RETURNING id;The sequence is:
- PostgreSQL tries to insert the row.
- The unique index detects an existing row with the same
(source_system, external_id). - Instead of raising an error, it runs the
DO UPDATEbranch against that existing row. RETURNING idgives you the internal key in either case.
The conflict columns in ON CONFLICT (...) must match a unique index exactly. If you list (external_id) but the only constraint is on (source_system, external_id), PostgreSQL raises an error saying there is no unique or exclusion constraint matching the ON CONFLICT specification.
Seeing the constraint work in Python
SQLite supports the same ON CONFLICT syntax for upserts and ships with Python, so you can verify the behavior without installing a database server.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute(
"CREATE TABLE customers ("
"id INTEGER PRIMARY KEY, "
"external_id TEXT NOT NULL UNIQUE, "
"name TEXT NOT NULL)"
)
rows = [("C-1001", "Ada Lovelace"), ("C-1002", "Grace Hopper")]
sql = (
"INSERT INTO customers (external_id, name) VALUES (?, ?) "
"ON CONFLICT(external_id) DO UPDATE SET name = excluded.name"
)
conn.executemany(sql, rows)
conn.executemany(sql, rows) # second run changes nothing
print(conn.execute("SELECT COUNT(*) FROM customers").fetchone()[0]) # 2Run it twice in your head: the first call inserts two rows, and the second finds both IDs already present and updates them in place. The count stays at 2.
Now see what a plain insert does against the same constraint:
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute(
"CREATE TABLE customers ("
"id INTEGER PRIMARY KEY, "
"external_id TEXT NOT NULL UNIQUE, "
"name TEXT NOT NULL)"
)
conn.execute("INSERT INTO customers (external_id, name) VALUES ('C-1001', 'Ada')")
try:
conn.execute("INSERT INTO customers (external_id, name) VALUES ('C-1001', 'Ada again')")
except sqlite3.IntegrityError as exc:
print("rejected:", exc)The constraint rejects the second insert with an IntegrityError. That error is the safety net: even if some code path forgets to use an upsert, the database refuses to create a duplicate.
Common errors
- No constraint at all.
ON CONFLICTfails to compile, or, if the code does a manual check-then-insert, concurrent writers create duplicates. Always add the constraint first. - Constraint columns differ from the conflict target. The statement errors out. Keep the two lists identical.
- Nullable match columns. Rows with
NULLexternal IDs bypass uniqueness. UseNOT NULL. - Constraint too narrow or too wide. A single-column constraint across several source systems causes collisions. Including extra columns, such as a name, makes the constraint useless because the same external ID with a changed name no longer conflicts.
- Unnormalized values.
c-1001,C-1001, andC-1001are three different strings to the database, so all three can coexist. Normalizing values before matching is covered in a later chapter. - Partial indexes not matched. If the unique index has a
WHEREcondition, theON CONFLICTclause must repeat that condition, or PostgreSQL will not use the index.
Checking your work
After adding the constraint, confirm it exists and does what you expect:
SELECT conname, pg_get_constraintdef(oid)
FROM pg_constraint
WHERE conrelid = 'customers'::regclass;Then try to insert a duplicate with a plain INSERT. It should fail. If it succeeds, the constraint is not in place or is scoped differently than you intended.
Exercise
A table has UNIQUE (external_id) only. Your pipeline now loads customers from two systems, and both issue the ID C-1001 for different people. What goes wrong when you upsert with ON CONFLICT (external_id), and what is the fix?
Show answer
The second system's record matches the first system's row, so the upsert overwrites that row's name and email, and one customer's data is lost with no error. The fix is to add a source_system column, make it NOT NULL, replace the constraint with UNIQUE (source_system, external_id), and change the conflict target to ON CONFLICT (source_system, external_id).
Exercise
You run ALTER TABLE customers ADD CONSTRAINT ... UNIQUE (source_system, external_id) and it fails with a duplicate key error. What do you do before retrying?
Show answer
Find the duplicated pairs with a GROUP BY source_system, external_id HAVING count(*) > 1 query. Decide which row to keep for each pair, merge or delete the others, and repoint any rows that reference the removed internal id values. Then add the constraint again.