Sub topic 7
Deciding Which Fields an Update Overwrites
This chapter assumes you can write the INSERT ... ON CONFLICT statement from the previous chapter. It also assumes that customers has a unique constraint on (source_system, external_id). Examples use PostgreSQL, plus one runnable Python/SQLite script.
Why the update branch needs a decision
An upsert has two outcomes. If no row matches the external ID, the insert branch writes every column you supplied. If a row matches, the DO UPDATE branch runs, and it writes only the columns you list in SET.
Nothing forces you to list all of them. Every column you leave out of SET keeps its stored value. This is the main control you have over what a repeated load can damage.
A careless version copies every incoming column into the existing row. That is wrong whenever someone or something else also writes to the table. Examples are a sales team that fills in account_manager, a trigger that maintains updated_at, or a second source system that supplies a better email. The next sync would erase their work without any error.
Sort columns by who owns them
Before you write SET, assign each column an owner.
| Column kind | Example | In the update branch |
|---|---|---|
| Match key | `source_system`, `external_id` | Never update. It is the basis of the match. |
| Internal key | `id` | Never update. Other tables may reference it. |
| Source-owned data | `name`, `email` | Overwrite from the incoming row. |
| Locally owned data | `account_manager` | Leave out of `SET`. |
| Audit columns | `created_at`, `updated_at` | `created_at` stays. `updated_at` is set explicitly. |
Updating the match key is pointless, because the row was found by those exact values. Updating id would break foreign keys. Leaving these out also makes the intent visible to a reviewer.
The table below adds a locally owned column and audit columns to the earlier customers table.
CREATE TABLE customers (
id bigserial PRIMARY KEY,
source_system text NOT NULL,
external_id text NOT NULL,
name text NOT NULL,
email text,
account_manager text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (source_system, external_id)
);The sync knows nothing about account_manager, so it never mentions that column. On insert the column is NULL. On update it is untouched.
How EXCLUDED works
Inside DO UPDATE, two names refer to two different rows:
customers.nameis the value already stored.EXCLUDED.nameis the value you tried to insert, which the conflict rejected.
SET name = EXCLUDED.name means "take the incoming value." You can also build values from both sides, which the next section uses.
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,
updated_at = now()
RETURNING id;This is a safe baseline. It never touches account_manager or created_at, and it sets updated_at itself.
Decide how to treat NULL
Source systems often send NULL for fields they do not know. That raises a question: does NULL mean "this value is now empty" or "I have no information"?
SET email = EXCLUDED.email treats it as an instruction to clear. If the CRM drops the email field from one export, every customer loses an email address.
SET email = COALESCE(EXCLUDED.email, customers.email) treats NULL as "no information" and keeps the stored value. The cost is that you can no longer clear an email through the sync.
Choose per column, based on what the source actually means:
- If the source always sends complete records, copy
NULLthrough. The source is the truth, including its blanks. - If the source sends partial records, use
COALESCE. Otherwise one sparse payload wipes out good data. - If you need both, the payload must say so. A separate flag or a distinct "clear this" marker lets you tell the two cases apart. A bare
NULLcannot.
Skip updates that change nothing
If you run the same load every night, most rows are identical to what is stored. By default PostgreSQL still writes a new row version for each one. It fires update triggers and bumps updated_at, and it leaves dead rows for vacuum to clean up. Worse, updated_at then stops meaning "the data changed."
A WHERE clause on DO UPDATE restricts the update to rows that would actually change. IS DISTINCT FROM is the right comparison because it treats two NULLs as equal. The ordinary <> returns NULL in that case, which counts as false.
INSERT INTO customers (source_system, external_id, name, email)
VALUES ('crm', 'C-1001', 'Ada King', NULL)
ON CONFLICT (source_system, external_id)
DO UPDATE SET name = EXCLUDED.name,
email = COALESCE(EXCLUDED.email, customers.email),
updated_at = now()
WHERE (customers.name, customers.email)
IS DISTINCT FROM
(EXCLUDED.name, COALESCE(EXCLUDED.email, customers.email))
RETURNING id;The right side of the comparison uses the same COALESCE expression as the SET list. If it did not, an incoming NULL email would always look different from the stored value, and the update would run for nothing.
Seeing it work
This Python script uses SQLite, which supports the same ON CONFLICT ... DO UPDATE ... WHERE form. SQLite spells the null-safe comparison IS NOT. The script follows these steps:
- It loads a customer.
- It simulates a local edit to
account_manager. - It reloads the customer with a new name and no email.
- It repeats that load unchanged.
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, "
"email TEXT, "
"account_manager TEXT)"
)
sql = (
"INSERT INTO customers (external_id, name, email) VALUES (?, ?, ?) "
"ON CONFLICT(external_id) DO UPDATE SET "
"name = excluded.name, "
"email = coalesce(excluded.email, customers.email) "
"WHERE customers.name IS NOT excluded.name "
"OR customers.email IS NOT coalesce(excluded.email, customers.email)"
)
conn.execute(sql, ("C-1001", "Ada Lovelace", "[email protected]"))
conn.execute(
"UPDATE customers SET account_manager = 'Sam' WHERE external_id = 'C-1001'"
)
first = conn.execute(sql, ("C-1001", "Ada King", None))
print(first.rowcount) # 1: the name changed
second = conn.execute(sql, ("C-1001", "Ada King", None))
print(second.rowcount) # 0: nothing differs, so no write
print(conn.execute(
"SELECT external_id, name, email, account_manager FROM customers"
).fetchone())
# ('C-1001', 'Ada King', '[email protected]', 'Sam')The final row shows all three decisions. The name came from the source. The email survived an incoming NULL. The locally edited account_manager was never touched.
How the decision flows
Common mistakes
- Listing every column in
SETby habit. It works until a second writer appears, then it silently destroys their data. - Updating
external_idorsource_system. A conflict on those columns means they already match, so the assignment does nothing useful. It also invites a second conflict if you ever change the target. - Relying on a trigger for
updated_atwhile also setting it inSET. Pick one place. Two writers of the same column make its meaning unclear. - Comparing with
<>in theWHEREclause. ANULLon either side makes the whole test unknown, so changes to or fromNULLare skipped. - Forgetting that the insert branch ignores these rules. On first load, every supplied column is written. The ownership rules above apply only to existing rows.
Choosing a policy
| Situation | Policy |
|---|---|
| The source is the only writer of the table | Overwrite all source columns, copy `NULL` through. |
| Others edit some columns | Leave those columns out of `SET`. |
| The source sends partial records | Use `COALESCE` on the optional columns. |
| Loads are large and mostly unchanged | Add the `IS DISTINCT FROM` guard. |
| Loads can arrive out of order | Add a timestamp guard, covered in a later chapter. |
Exercise
A nightly sync upserts customers keyed on (sourcesystem, externalid). Support staff manually correct the phone column in your table, and the source system never sends a phone value. A new developer proposes adding phone = EXCLUDED.phone to the SET list "for completeness". What happens, and what should the SET list do with phone?
Show answer
The source sends no phone, so EXCLUDED.phone is NULL. Adding phone = EXCLUDED.phone would overwrite every manually corrected phone number with NULL on the next run. Phone is locally owned, so it should be left out of SET entirely. The insert branch can still leave it NULL for new rows, and the update branch then never touches it.
Exercise
Your upsert has WHERE customers.email <> EXCLUDED.email. A customer's stored email is NULL and the source now sends "[email protected]". Does the row update? What should the condition use instead?
Show answer
No. Comparing anything with NULL using <> yields NULL, which the WHERE clause treats as false, so the update is skipped and the new email never arrives. Use customers.email IS DISTINCT FROM EXCLUDED.email, which treats NULL as an ordinary comparable value.