Sub topic 5
Writing the upsert with INSERT ... ON CONFLICT
This chapter assumes you know basic SQL (INSERT, UPDATE, SELECT, primary keys) and that you have a table with a unique constraint on the external ID. The examples use PostgreSQL. SQLite supports the same ON CONFLICT syntax.
The working model
An upsert is one statement that inserts a row or, if a matching row already exists, updates it. PostgreSQL does this with INSERT ... ON CONFLICT. The database tries the insert first. If the insert would violate the unique constraint you named, it runs the conflict action instead.
The match is made by the database, atomically, using the constraint. Your code does not need a SELECT followed by an INSERT or UPDATE.
The table
The upsert depends on this table. It has its own primary key, plus a unique constraint on the external ID scoped by source 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 statement
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 statement has three parts:
- Conflict target.
ON CONFLICT (source_system, external_id)names the columns of the unique constraint. They must match a unique index or constraint exactly. - Conflict action.
DO UPDATE SET ...changes the existing row.DO NOTHINGskips the row instead. EXCLUDED. This is a pseudo-table holding the row you tried to insert.EXCLUDED.nameis the incoming name.customers.nameis the stored name.
RETURNING id gives you the internal key whether the row was created or updated. You can use it to link other tables to the customer.
Conditional updates
You can add a WHERE to DO UPDATE. The update then runs only when the condition is true.
ALTER TABLE customers ADD COLUMN source_updated_at timestamptz;
INSERT INTO customers (source_system, external_id, name, email, source_updated_at)
VALUES ('crm', 'C-1001', 'Ada King', '[email protected]', '2026-11-30T12:00:00Z')
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name,
email = EXCLUDED.email,
source_updated_at = EXCLUDED.source_updated_at
WHERE customers.source_updated_at IS NULL
OR customers.source_updated_at < EXCLUDED.source_updated_at;If the stored row is newer than the incoming data, the update is skipped and the stored row stays as it was.
Seeing idempotence
The same pattern works in SQLite. Running the batch twice leaves the same two rows.
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]) # 2Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `there is no unique or exclusion constraint matching the ON CONFLICT specification` | The conflict target lists columns with no matching unique constraint or index. | Add the constraint, or change the target to match it. |
| `RETURNING` gives no row | The action was `DO NOTHING`, or the `WHERE` on `DO UPDATE` was false. | Do not assume a row always comes back. Fall back to a `SELECT` when it is empty. |
| `ON CONFLICT DO UPDATE command cannot affect row a second time` | One statement contains the same external ID twice. | Remove duplicates from the batch first. |
| Wrong values written | `SET name = name` or a stored column used where `EXCLUDED` was meant. | Use `EXCLUDED.column` for incoming values. |
The duplicate-in-batch error comes up again in the chapter on batches.
Exercise
You run the upsert from this chapter for ('crm', 'C-1001') and the stored row already has a newer sourceupdatedat than the incoming row. The statement has a WHERE on DO UPDATE and ends with RETURNING id. What happens to the stored row, and what does RETURNING produce?
Show answer
The stored row is left unchanged because the WHERE condition is false, so the update is skipped. RETURNING produces no row, because no row was inserted or updated. Code that reads the returned id must handle the empty result.