Sub topic 1
What an upsert is and why it replaces insert-or-update logic
Prerequisites
This chapter assumes you can do the following:
- Write basic SQL:
INSERT,UPDATE,SELECT, and define a primary key. - Read a table definition with constraints such as
NOT NULLandUNIQUE. - Read short Python scripts. The runnable example uses the standard
sqlite3module. - Understand that data is often copied between separate systems, such as a CRM and your own database.
Later chapters cover external IDs, unique constraints, and batches in detail. This chapter explains the problem an upsert solves and shows the idea in a small working form.
What an upsert is
An upsert is a single write operation with two possible outcomes:
- If no record matches, it inserts a new one.
- If a record matches, it updates the existing one.
The name combines "update" and "insert". The match is decided by a key you choose, not by guessing. When the data comes from another system, that key is usually the other system's identifier, called an external ID. For example, your CRM may call a customer C-1001. Your database stores that value and uses it to decide whether an incoming record is new or already known.
The important property is that the database makes the decision, inside one statement. Your application does not look first and then act.
The logic an upsert replaces
Without an upsert, most people write insert-or-update as three steps in application code:
- Run a
SELECTto see whether the record exists. - If it does not exist, run an
INSERT. - If it exists, run an
UPDATE.
This works in a test with one writer. It has three weaknesses in real use.
It takes more round trips. Each record costs a read and a write. For a load of 100,000 records, that is 200,000 statements instead of 100,000.
It is not safe under concurrency. The SELECT and the write are separate steps, and another writer can act between them. This is a race condition, where the result depends on the timing of two actors.
It is easy to get subtly wrong. The branching logic lives in application code, so each script that loads data may implement it differently. One script may forget to update a field. Another may skip the existence check entirely.
How the check-then-write approach fails
Suppose two workers receive the same customer, C-1001, at nearly the same moment. Each one runs the check-then-write routine.
What happens at the last step depends on your schema:
- With a unique constraint on the external ID, worker B's insert raises an error. The load fails, or you must add retry logic.
- Without a unique constraint, worker B's insert succeeds. You now have two rows for one customer, and every later query has to deal with that.
Wrapping the code in a transaction does not reliably fix this. At the default isolation level in many databases, both transactions can still read "no rows" before either commits. Using a stricter isolation level can help, but you then have to handle serialization failures and retry. The upsert avoids this by moving the decision into the single statement that does the write.
The upsert in PostgreSQL
PostgreSQL implements an upsert as INSERT ... ON CONFLICT. It depends on a unique constraint, so we first define one:
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 table keeps its own primary key, id. The pair (source_system, external_id) is the match key, and the UNIQUE constraint is what makes the match reliable. The source_system column matters because two systems may both use the ID 1001 for different customers.
Now the upsert itself:
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:
INSERT ... VALUESis the normal insert. The database tries it first.ON CONFLICT (source_system, external_id)names the unique constraint that counts as a match. If the insert would violate it, the database does not raise an error.DO UPDATE SET ...says what to do instead.EXCLUDEDis a name for the row you tried to insert, soEXCLUDED.namemeans the incoming name.
RETURNING id gives back the internal primary key, whether the row was just created or already existed. That is useful when you need to link other records to the customer.
If you run this statement when no row exists, it inserts one. If you run it again with the same external ID, it updates that row. The row count stays at one.
The same idea in other systems
The syntax differs between databases, but the concept does not.
| System | Upsert form | Match is decided by |
|---|---|---|
| PostgreSQL | `INSERT ... ON CONFLICT ... DO UPDATE` | The named unique index or constraint |
| SQLite (3.24 and later) | `INSERT ... ON CONFLICT ... DO UPDATE` | The named unique index or constraint |
| MySQL | `INSERT ... ON DUPLICATE KEY UPDATE` | Any unique or primary key that conflicts |
| SQL standard | `MERGE` | An explicit join condition in the statement |
In every case, the match rule is tied to the database's own uniqueness checking. This is why the constraint matters more than the syntax.
A runnable comparison
The following Python script uses SQLite, which ships with Python. It shows the failure from the diagram and then shows the upsert avoiding it. The between argument runs code between the check and the write, which simulates another worker acting in that gap.
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)"
)
def save_naive(external_id, name, between=None):
row = conn.execute(
"SELECT id FROM customers WHERE external_id = ?", (external_id,)
).fetchone()
if between:
between() # another writer acts here
if row is None:
conn.execute(
"INSERT INTO customers (external_id, name) VALUES (?, ?)",
(external_id, name),
)
else:
conn.execute(
"UPDATE customers SET name = ? WHERE id = ?", (name, row[0])
)
def save_upsert(external_id, name):
conn.execute(
"INSERT INTO customers (external_id, name) VALUES (?, ?) "
"ON CONFLICT(external_id) DO UPDATE SET name = excluded.name",
(external_id, name),
)
def rival_insert():
conn.execute(
"INSERT INTO customers (external_id, name) VALUES ('C-1001', 'Rival')"
)
try:
save_naive("C-1001", "Ada Lovelace", between=rival_insert)
except sqlite3.IntegrityError as exc:
print("naive version failed:", exc)
save_upsert("C-1001", "Ada Lovelace")
save_upsert("C-1001", "Ada Lovelace")
print(conn.execute("SELECT external_id, name FROM customers").fetchall())The naive version reads "no row", the rival insert creates the row, and the naive insert then hits the UNIQUE constraint and raises IntegrityError. The upsert has no gap to fall into. It runs twice and the table still holds one row, with the name set to the incoming value.
Edge cases to know early
These are covered in later chapters. Knowing them now prevents false confidence.
- No constraint, no upsert.
ON CONFLICTcan only match against a unique index or constraint. If you name columns that have no such constraint, PostgreSQL rejects the statement. Without the constraint, there is nothing for the database to detect a conflict against. - NULL never matches. In PostgreSQL, a
NULLin a unique column is treated as different from every otherNULLby default. A row with a missing external ID will never conflict, so you would get duplicates. Declare the columnNOT NULL, as the table above does. - Updates overwrite by default.
DO UPDATEreplaces the columns you list, with no regard for which version of the data is newer. A late-arriving old record can overwrite a newer one. Choosing which fields to overwrite, and guarding against stale data, are separate design decisions. - One row per key per statement. PostgreSQL does not allow a single
INSERT ... ON CONFLICT DO UPDATEto affect the same row twice. If a batch contains the same external ID twice, the statement fails. Batches need deduplication first. - An upsert does not remove the need to clean IDs.
C-1001andc-1001are different strings. If your sources format IDs inconsistently, the upsert will faithfully create two rows.
What to remember
- An upsert is insert-or-update in one statement, decided by a match key.
- It replaces the select-then-write pattern, which costs extra round trips and breaks when two writers overlap.
- The database can only decide a match through a unique constraint, so the constraint is part of the design.
- Repeating the same upsert leaves the same result, a property called idempotence, which the next chapters build on.
Exercise
A load script runs SELECT id FROM customers WHERE external_id = 'C-2000', gets no rows, and then runs an INSERT for that ID. The table has no unique constraint on external_id. Two copies of the script run at the same time. What can go wrong, and what two changes make the load safe?
Show answer
Both scripts can see no row and both insert, which leaves two rows for the same customer. Add a UNIQUE (and NOT NULL) constraint on the external ID, or on (source_system, external_id), so the database rejects duplicates. Then replace the select-then-write logic with a single INSERT ... ON CONFLICT ... DO UPDATE statement keyed on that constraint, so the match decision happens inside the database in one step.
Exercise
In the PostgreSQL upsert above, what does EXCLUDED.name refer to, and what does RETURNING id give you when the row already existed?
Show answer
EXCLUDED.name is the name value from the row you attempted to insert, that is, the incoming value. RETURNING id returns the internal primary key of the existing row that was updated, the same as it would for a newly inserted row.