Sub topic 2
Writing the Upsert with `INSERT ... ON CONFLICT`
Assume you know INSERT, UPDATE, SELECT, primary keys, and unique constraints. An upsert combines an insert and an update. PostgreSQL inserts a row when no matching key exists. When a unique key conflicts, PostgreSQL updates the existing row instead.
Write the upsert
Keep your internal primary key separate from the identifier owned by another system:
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)
);The unique constraint makes the pair of source system and external ID a reliable match key. The same external ID can appear in two source systems without causing a conflict.
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;EXCLUDED means the values from the attempted insert. The statement returns the internal id whether it inserted a new row or updated an existing one.
Run the same load safely
An upsert is idempotent when repeating the same input produces the same database state. The unique constraint prevents a second row, and the conflict action updates the existing row.
Do not assume every upsert is automatically idempotent. If the update includes changing values such as updated_at, repeated runs can still change the row. Define which fields should change and confirm the result with a row count.
Choose update fields
Update fields received from the source, such as name and email. Leave locally managed fields, such as review status or internal notes, out of DO UPDATE SET. An omitted column keeps its stored value.
Normalize before matching
Normalize external IDs before the upsert. Apply the same rules to every load, such as trimming surrounding spaces or converting IDs to uppercase. Otherwise c-1001 and C-1001 may become separate records. Store the normalized value, and preserve the original value separately only when auditing requires it.
Exercise
Which part prevents a repeated load from inserting a duplicate customer?
Show answer
The UNIQUE (sourcesystem, externalid) constraint, together with ON CONFLICT using those columns.