Sub topic 1
What an Upsert Is and Why It Replaces Insert-or-Update Logic
Prerequisites
This chapter assumes you know:
- Basic SQL:
INSERT,UPDATE,SELECT, and primary keys. - How relational tables and constraints work, especially
UNIQUE. - That data is often copied between separate systems, such as a CRM and your own database.
The examples use PostgreSQL 9.5 or later.
The problem: insert or update?
Suppose you load customer records from a CRM into your own database. Each run delivers some customers you have never seen and some you already stored. For each record you must choose between INSERT and UPDATE.
The usual first attempt looks like this:
- Run a
SELECTto check whether the record exists. - If it does not, run an
INSERT. - If it does, run an
UPDATE.
This has two weaknesses.
- It costs two round trips per record. That adds up when you load thousands of rows.
- It is not safe with concurrent writers. Two processes can both run the
SELECT, both see no row, and both run theINSERT. Without a unique constraint you get duplicates. With one, the second process fails with an error and your application has to handle it.
What an upsert does
An upsert is a single statement that inserts a row if no matching row exists and updates the existing row otherwise. The name combines "update" and "insert". The database does the check and the write as one operation, so no other writer can slip in between them.
The match key
The database must know what "the same record" means. That is the match key, and it must be backed by a unique constraint or unique index. When a record comes from another system, the key is usually that system's own identifier, called an external ID. Later chapters cover choosing and cleaning external IDs. Here, one column is enough.
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)
);Your first upsert
In PostgreSQL, an upsert is INSERT ... ON 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;Read it in three parts:
ON CONFLICT (source_system, external_id)names the match key. A conflict means the insert would violate that unique constraint.DO UPDATE SET ...runs when a conflict occurs.EXCLUDEDis the row you tried to insert, soEXCLUDED.nameis the incoming name.RETURNING idgives you the internal key whether the row was created or updated.
Run it once and the table has one row. Run it again with a changed name and the table still has one row, now with the new name.
Common errors
- No matching constraint. If the columns in
ON CONFLICT (...)do not match a unique constraint or unique index exactly, PostgreSQL rejects the statement. The error says there is no unique or exclusion constraint matching theON CONFLICTspecification. - Confusing
DO NOTHINGwithDO UPDATE.DO NOTHINGskips conflicting rows and leaves the stored data unchanged. Use it only when existing rows should never be modified. - Updating the key itself. Do not set the match columns in
DO UPDATE SET. The key identifies the row and should stay stable.
Exercise
A colleague writes INSERT INTO customers (...) VALUES (...) ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name, but the table only has a unique constraint on (source_system, external_id). What happens, and how do you fix it?
Show answer
PostgreSQL rejects the statement because no unique constraint or index matches ON CONFLICT (email). Either change the conflict target to (source_system, external_id), which is the intended match key, or add a unique constraint on email if email really identifies a customer.