Upsert and External IDs
By the end of this lesson, you'll be able to:
- Use upsert to insert-or-update based on the standard Id field
- Explain what an external Id field is and why it exists
- Use upsert with an external Id field to match records from an outside system
Prerequisites: "Update"
upsert with the standard Id
Account acc = new Account(Name = 'Riverbend Farms');
upsert acc; // no Id yet — this inserts
acc.Industry = 'Agriculture';
upsert acc; // now has an Id — this updates
The exact same statement, upsert acc, does an insert the first time (no Id present) and an update the second time (an Id now exists) — no need to write separate insert/update logic and check which one applies yourself.
The problem external Ids solve
Imagine importing customer records from an external CRM system nightly. Each import needs to know: "does this customer already exist in Salesforce, or is this new?" The external system's own customer ID — not Salesforce's internal Id — is what naturally identifies "the same customer" across both systems. An external Id field (a custom field marked as an External ID) lets upsert match on that value instead of Salesforce's own Id.
Using upsert with an external Id field
List<Account> importedAccounts = new List<Account>{
new Account(Name = 'Riverbend Farms', External_Customer_Id__c = 'CRM-4471'),
new Account(Name = 'Northwind Traders', External_Customer_Id__c = 'CRM-4472')
};
upsert importedAccounts External_Customer_Id__c;
upsert importedAccounts External_Customer_Id__c tells Salesforce to match each incoming record against existing Accounts by comparing External_Customer_Id__c, not the internal Id — a record whose External_Customer_Id__c already exists gets updated; a new one gets inserted. This is the standard, safe way to repeatedly sync data from an outside system without creating duplicates.
Exercise
As a comment, explain why matching on an external Id field is more useful than the standard Id for a nightly import from another system.
Show hint
Think about which system actually knows the record's identity first.
Upsert and External IDs Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
upsert inserts a record if it doesn't already exist and updates it if it does — genuinely useful once you add an external Id field for matching records that originate outside Salesforce.