Sub topic 8
External IDs and upsert for repeatable loads
This chapter explains why sf data import tree is awkward to run twice, and how an external ID field with an upsert makes a load repeatable. It assumes you have read the earlier chapters on plan files and tree import. You should be comfortable with a Salesforce DX project layout, CSV files, and the sf CLI authorized to a scratch org.
Why a plain import is not repeatable
Tree import inserts every record in its data files. Run the same plan twice and you get two copies of every Account and Contact. Salesforce also assigns a new 18-character record ID on each insert, so you cannot use those IDs in your files to say "this record again".
A repeatable load needs a key that you control and that survives from one run to the next. That key is an external ID.
What an external ID is
An external ID is a custom field marked as an identifier from a system outside Salesforce. Here, the "outside system" is your seed files. The field gives each seed record a stable name such as ACC-001.
Marking a field as an external ID has three effects:
- The field is indexed, so lookups by it are fast.
- Upsert operations can match records on it.
- Other records can point at a record through it, without knowing the Salesforce ID.
External ID fields can be Text, Number, Email, or Auto Number. Text is the usual choice for seed data.
Make the field unique as well. If two records could share a value, an upsert that matches on it would be ambiguous, and Salesforce rejects such a load.
Creating the field in source
Define the field as metadata in your project so that every scratch org gets it from a normal deploy. Save this as force-app/main/default/objects/Account/fields/External_Id__c.field-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>External_Id__c</fullName>
<label>External Id</label>
<type>Text</type>
<length>50</length>
<externalId>true</externalId>
<unique>true</unique>
<caseSensitive>false</caseSensitive>
<required>false</required>
</CustomField>Create the same field on Contact if you want to upsert Contacts too. Deploy with sf project deploy start before loading any data. Users also need field-level security on the field. Without it, an upsert run as a non-admin user may fail with an "invalid field" style error.
What upsert does
Upsert is "update or insert". For each row, Salesforce looks for an existing record whose external ID field equals the value in the row.
- If one record matches, Salesforce updates it.
- If none matches, Salesforce inserts a new record.
- If more than one matches, the row fails. A unique field prevents this.
Because the outcome depends only on the key, running the same file twice leaves the org in the same state after the second run as after the first. This property is called idempotence, and it is the reason to use upsert for seed data.
Upserting from a CSV file
Here is a small CSV file, data/accounts.csv:
External_Id__c,Name,Industry
ACC-001,Acme Robotics,Technology
ACC-002,Blue Harbor Software,Technology
ACC-003,Cedar Analytics,TechnologyLoad it with the bulk upsert command:
sf data upsert bulk \
--sobject Account \
--file data/accounts.csv \
--external-id External_Id__c \
--target-org my-scratch \
--wait 10The flags do the following:
| Flag | Purpose |
|---|---|
| `--sobject` | The object to load into |
| `--file` | The CSV file. The first row must hold field API names |
| `--external-id` | The field used to match existing records |
| `--target-org` | Alias or username of the org |
| `--wait` | Minutes to wait for the job to finish before the command returns |
Run the command a second time. The job reports the same number of processed records, but the Account count in the org does not change. If you edit a Name in the CSV and run it again, the existing Account is updated in place.
The CSV header must contain the external ID column. Every row needs a value in it. A blank value is treated as "no match", so the row is inserted, and the next run inserts it again. This is a common source of duplicates.
Relating child records through an external ID
An external ID also solves the relationship problem. The tree format needs @AccountRef1 references and a plan that saves them. A CSV upsert can point to the parent by its external ID instead.
Suppose Contact also has an External_Id__c field. A Contact file can name the parent Account with a relationship column:
External_Id__c,FirstName,LastName,Email,Account.External_Id__c
CON-001,Ada,Lovelace,[email protected],ACC-001
CON-002,Grace,Hopper,[email protected],ACC-001
CON-003,Alan,Turing,[email protected],ACC-002The header Account.External_Id__c means "the Account whose ExternalId_c equals this value". Load the Accounts first, then the Contacts:
sf data upsert bulk --sobject Account --file data/accounts.csv \
--external-id External_Id__c --target-org my-scratch --wait 10
sf data upsert bulk --sobject Contact --file data/contacts.csv \
--external-id External_Id__c --target-org my-scratch --wait 10Order still matters. If a Contact names ACC-009 and no such Account exists yet, that row fails with an error about the unresolved relationship. Load parents before children, as you did when designing the dataset.
Upserting from Apex
The same idea works in an anonymous Apex script. Database.upsert takes the external ID field as a Schema.SObjectField token:
List<Account> accounts = new List<Account>{
new Account(External_Id__c = 'ACC-001', Name = 'Acme Robotics', Industry = 'Technology'),
new Account(External_Id__c = 'ACC-002', Name = 'Blue Harbor Software', Industry = 'Technology')
};
Database.UpsertResult[] results =
Database.upsert(accounts, Account.External_Id__c, false);
for (Database.UpsertResult r : results) {
if (!r.isSuccess()) {
System.debug('Failed: ' + r.getErrors()[0].getMessage());
} else {
System.debug((r.isCreated() ? 'Inserted ' : 'Updated ') + r.getId());
}
}The third argument, false, means partial success is allowed. Failed rows are reported in the results instead of throwing an exception and rolling back the whole call. For seed scripts, you usually want to see all failures at once, so this is a good default. Run the script with sf apex run --file scripts/apex/seed.apex.
To link a child to its parent in Apex without querying, build a reference object that carries only the external ID:
Account parentRef = new Account(External_Id__c = 'ACC-001');
Contact c = new Contact(
External_Id__c = 'CON-001',
FirstName = 'Ada',
LastName = 'Lovelace',
Account = parentRef
);
Database.upsert(new List<Contact>{ c }, Contact.External_Id__c, false);Choosing external ID values
Good keys make the seed set easy to read and hard to break.
- Use readable, fixed strings like
ACC-001. Do not generate random values at load time, because a new value on each run defeats the match. - Use a prefix per object, so a Contact key never looks like an Account key.
- Keep keys in version control with the data. The key is part of the dataset's identity.
- If you export from a real org, do not reuse real Salesforce IDs as keys. They differ between orgs.
Limits of upsert as a seeding tool
Upsert makes loads repeatable, but it has boundaries you should know.
- It never deletes. If you remove a row from the CSV, the record from the earlier run stays in the org. To reset the data, delete it first or create a new scratch org.
- It updates only the fields present in the file. A field you set by hand in the org and left out of the CSV keeps its value.
- Validation rules, required fields, and triggers run on upsert, as they do on any insert or update. A rule that blocks inserts can fail the load even if the data looks right.
- A row that matches a record the running user cannot edit fails as an update.
Common errors
| Symptom | Likely cause |
|---|---|
| Duplicates after a second run | Blank or changed external ID values, so rows were treated as new |
| Error naming the external ID field as invalid | Field not deployed, or no field-level security for the running user |
| Child rows fail with a relationship error | Parent not loaded yet, or the parent key does not match exactly |
| "Duplicate external id" style failure | The same key appears on several rows in one file, or non-unique values already exist in the org |
| Job finishes but nothing appears | `--wait` expired and the job is still running. Check the job status in Setup under Bulk Data Load Jobs |
If --wait is too short, the command returns before the job ends. The job keeps running on the server, so check it rather than re-running at once.
Exercise
You run sf data upsert bulk with --external-id External_Id__c on a CSV of 100 Accounts, and it succeeds. You then change the Name of the row ACC-007 in the CSV, delete the row ACC-050, and run the same command again. How many Accounts does the org hold afterwards, and what happened to ACC-007 and ACC-050?
Show answer
The org still holds 100 Accounts. ACC-007 matched an existing record, so its Name was updated and no new record was created. ACC-050 is no longer in the file, so nothing touched it. Upsert never deletes, and the old record stays unchanged.
Exercise
A Contact CSV uses the column Account.External_Id__c. Half the rows fail, and the error says the Account reference could not be resolved. Name two things to check.
Show answer
First, check that the Accounts were loaded before the Contacts, since a parent must exist before a child can point to it. Second, check that the values in the Contact column match the Account External_Id__c values exactly, including case, spacing, and prefix. A typo or trailing space produces an unmatched key.