Sub topic 10
Upserting with an external ID field
An upsert is a single operation that updates a record if it already exists and inserts it if it does not. In a bulk load, this lets you send the same file repeatedly without creating duplicates. This chapter assumes you can already create an ingest job, upload CSV data, close the job with UploadComplete, and read the result files. It also assumes you know what an external ID field is in the Salesforce data model.
Why upsert instead of insert or update
Plain insert always creates records. Run it twice and you get two copies of every row. Plain update needs the Salesforce record Id for every row, which means you must query for IDs before you can load.
Upsert avoids both problems. Your source system already has its own key for each record, such as a customer number or an ERP identifier. If you store that key in a Salesforce field marked as an external ID, Salesforce can match rows to records using your key. You never need to know the Salesforce Id.
This makes upsert a good fit for:
- Repeated synchronization from another system, where the same file may be loaded nightly.
- Reloading a file after a partial failure, because rows that already succeeded are matched and updated rather than duplicated.
- Loading parent and child data in one pass, because child rows can reference parents by external ID.
Requirements for the external ID field
The field you match on must meet these conditions:
- It is a custom field marked External ID on the target object, or a standard field that Salesforce indexes for lookup.
- It is a text, number, or email type. Other field types cannot be external IDs.
- Ideally it is also marked Unique. Without uniqueness, two records can carry the same value, and a row that matches both cannot be resolved.
The examples below assume a custom text field Legacy_Id__c on Contact, marked External ID and Unique.
How Salesforce matches each row
For every row, Salesforce looks up the value in the external ID column and chooses one of three outcomes.
Matching on a field that is not case-sensitive treats ab-100 and AB-100 as the same value. If your source system distinguishes them, either make the field case-sensitive and unique, or normalize values before upload.
The CSV file
The file must include a column for the external ID field, named by its API name. All other columns are ordinary fields to set on insert or update.
Legacy_Id__c,FirstName,LastName,Email
C-1001,Ada,Lovelace,[email protected]
C-1002,Alan,Turing,[email protected]
C-1003,Grace,Hopper,[email protected]Two practical rules apply:
- Remove duplicate external ID values from the file before you upload. Two rows with the same key in one job compete with each other, and one of them can fail or, on a non-unique field, create two records.
- Do not leave the external ID value blank. A blank key cannot be matched, so treat blank keys as a data-quality problem and filter them out upstream.
Creating the upsert job
The only differences from an insert job are the operation value and one extra property, externalIdFieldName.
curl -X POST "$INSTANCE_URL/services/data/v62.0/jobs/ingest" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"object": "Contact",
"operation": "upsert",
"externalIdFieldName": "Legacy_Id__c",
"contentType": "CSV",
"lineEnding": "LF"
}'The response has the same shape as for an insert job. It contains the job id, the state Open, and the externalIdFieldName you supplied. If you omit externalIdFieldName on an upsert job, or name a field that is not an external ID, Salesforce rejects the request.
From here the steps are unchanged. Upload the CSV with PUT .../batches, then PATCH the state to UploadComplete, then poll the job until it reaches a terminal state.
Reading the results
Upsert results use the same three result endpoints as other ingest jobs. The successful results file adds one column that matters here.
| Column | Meaning in a successful upsert |
|---|---|
| `sf__Id` | The Salesforce `Id` of the record that was created or updated. |
| `sf__Created` | `true` if the row inserted a new record, `false` if it updated an existing one. |
| Original columns | Your submitted values, repeated after the `sf__` columns. |
A successful results file for the earlier CSV, run when Ada already existed, might look like this:
"sf__Id","sf__Created","Legacy_Id__c","FirstName","LastName","Email"
"003xx0000012345AAA","false","C-1001","Ada","Lovelace","[email protected]"
"003xx0000012346AAA","true","C-1002","Alan","Turing","[email protected]"
"003xx0000012347AAA","true","C-1003","Grace","Hopper","[email protected]"Count the sf__Created values to confirm that a load behaves as you expect. A nightly sync that should only update, but reports thousands of true values, usually means the keys in the file do not match what is stored in Salesforce. Common causes are leading zeros dropped by a spreadsheet and trailing whitespace.
Failed rows appear in failedResults/ with sf__Id and sf__Error columns, followed by your original columns. Rows in unprocessedrecords/ were never attempted, for example because the job was aborted or failed early.
Script: upsert and summarize
This script creates the job, uploads the file, closes the upload, waits for a terminal state, and then counts inserts and updates from the successful results.
import csv
import io
import os
import time
import requests
instance = os.environ["SF_INSTANCE_URL"]
token = os.environ["SF_ACCESS_TOKEN"]
base = f"{instance}/services/data/v62.0/jobs/ingest"
auth = {"Authorization": f"Bearer {token}"}
job = requests.post(
base,
headers=auth,
json={
"object": "Contact",
"operation": "upsert",
"externalIdFieldName": "Legacy_Id__c",
"contentType": "CSV",
"lineEnding": "LF",
},
)
job.raise_for_status()
job_id = job.json()["id"]
with open("contacts_upsert.csv", "rb") as f:
requests.put(
f"{base}/{job_id}/batches",
headers={**auth, "Content-Type": "text/csv"},
data=f,
).raise_for_status()
requests.patch(
f"{base}/{job_id}", headers=auth, json={"state": "UploadComplete"}
).raise_for_status()
while True:
resp = requests.get(f"{base}/{job_id}", headers=auth)
resp.raise_for_status()
info = resp.json()
if info["state"] in ("JobComplete", "Failed", "Aborted"):
break
time.sleep(10)
print("State:", info["state"], "Failed rows:", info.get("numberRecordsFailed"))
ok = requests.get(f"{base}/{job_id}/successfulResults/", headers=auth)
ok.raise_for_status()
rows = list(csv.DictReader(io.StringIO(ok.content.decode("utf-8"))))
created = sum(1 for r in rows if r["sf__Created"].lower() == "true")
print(f"Inserted: {created}, Updated: {len(rows) - created}")Linking records through external IDs
Upsert also helps with relationships. Instead of putting a parent's Salesforce Id in a lookup column, you can reference the parent by its external ID. In the CSV header, you write the relationship name, a dot, and the parent's external ID field, for example Account.Legacy_Id__c (a custom relationship uses the __r form of its name). Salesforce resolves the parent for you, so you can load children without first querying for parent IDs. Check the Bulk API 2.0 documentation for the exact header format your object needs, because custom and polymorphic relationships differ.
The parent records must already exist when the child job runs. Run the parent job to completion first.
Common errors
- Field is not an external ID. The job is rejected at creation. Confirm the field's External ID checkbox in Setup, and check that the API name is spelled exactly, including the
__csuffix. - Duplicate matches. Rows fail with a duplicate-value message. Check the Unique setting and look for existing records that share a key.
- Missing key column. If the CSV header omits the external ID column, rows cannot be matched. Make sure the header name matches the API name exactly.
- Keys that look equal but are not. Spreadsheets strip leading zeros and add spaces. Export keys as text, and trim them before upload.
- Field-level security. The integration user needs access to the external ID field, or the match fails.
Exercise
A nightly upsert job on Contact, matched on LegacyIdc, finishes with JobComplete and zero failed rows. However, the successful results show sf_Created = true for almost every row, and the Contact count in the org has doubled. What is the most likely cause, and how would you confirm it?
Show answer
The external ID values in the file do not match the values already stored in Salesforce, so every row is treated as new and inserted. Likely causes are leading zeros removed by a spreadsheet, extra whitespace, or a different key format. Confirm it by comparing a few keys from the file with the LegacyIdc values on existing records, for example with a bulk query on LegacyId__c. Fix the key formatting in the source file, remove the duplicate records that were created, and rerun the upsert.