Sub topic 16
Unique and External ID Fields, and How They Affect Queries
This chapter assumes you can create custom fields in Object Manager. It also assumes you know basic SOQL and have seen an Apex insert statement. By the end you should be able to mark a field unique or as an external ID, explain what each setting enforces, and predict how each affects query speed and data loading.
Two settings, two jobs
Unique and External ID are separate checkboxes on a custom field. They solve different problems, and they are often used together.
- Unique is a constraint. Salesforce rejects any save that would give two records the same value in that field.
- External ID is a label. It tells Salesforce that this field holds the record's identifier from another system, so integrations can use it to match records.
| Setting | What it does | Available on |
|---|---|---|
| Unique | Blocks duplicate values, with a case-sensitivity choice for text | Text, Email, Number |
| External ID | Allows upsert matching and parent references by this field | Text, Email, Number, Auto Number |
An object can have up to 25 external ID fields. Encrypted fields cannot be unique or external IDs.
How unique fields behave
A few details cause most of the surprises.
- Case sensitivity. For text fields you choose whether
ABC-1andabc-1count as the same value. The default is case-insensitive, so those two values collide. A case-sensitive field treats them as different records. - Blanks are allowed. Several records may leave a unique field empty. Blanks are not compared with each other.
- Existing duplicates block the change. You cannot turn on Unique while the field already holds duplicate values. Clean the data first, then enable the setting.
- Failures are row-level. A duplicate raises
DUPLICATE_VALUEon that record. In a bulk load the other rows can still succeed if you allow partial success.
Here is a text field marked both unique and external ID, in metadata format:
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>ERP_Id__c</fullName>
<label>ERP Id</label>
<type>Text</type>
<length>40</length>
<required>false</required>
<unique>true</unique>
<caseSensitive>false</caseSensitive>
<externalId>true</externalId>
</CustomField>What an external ID gives you
Many integrations know a record by the ID in their own system, such as an ERP customer number. They do not know the 18-character Salesforce ID. An external ID field lets them work with the ID they already have.
Upsert
An upsert is an insert or an update, chosen per record. Salesforce looks for an existing record whose external ID matches. If it finds one, it updates that record. If it finds none, it inserts a new one.
List<Account> accounts = new List<Account>{
new Account(Name = 'Acme Corp', ERP_Id__c = 'ERP-1001'),
new Account(Name = 'Globex', ERP_Id__c = 'ERP-1002')
};
Database.UpsertResult[] results =
Database.upsert(accounts, Account.ERP_Id__c, false);
for (Database.UpsertResult r : results) {
System.debug(r.isCreated() ? 'Inserted ' + r.getId() : 'Updated ' + r.getId());
}Running this twice creates two accounts the first time and updates the same two the second time. No duplicates appear.
The match must find at most one record. If the external ID is not also unique and two records share a value, the upsert fails for that row. Combine the two settings for any field you use as an integration key.
Parent references without Salesforce IDs
You can point a new child record at its parent by the parent's external ID. This saves a query to look up the parent's Salesforce ID first.
Contact c = new Contact(
LastName = 'Lee',
Account = new Account(ERP_Id__c = 'ERP-1001')
);
insert c;Data Loader, the REST API and the Bulk API support the same pattern. In REST, an upsert is a PATCH to /services/data/vXX.0/sobjects/Account/ERP_Id__c/ERP-1001.
Indexes and query performance
Salesforce automatically indexes fields marked unique or external ID. The query optimizer can use that index to find rows without scanning the whole object, so filtering on these fields is fast.
Some fields are indexed with no setup. They include Id, Name, OwnerId, CreatedDate, SystemModstamp, lookup and master-detail fields, and record type. Unique and external ID are the main ways to add an index to your own text, number or email fields. For other fields you can ask Salesforce Support to create a custom index.
Selective queries
An index helps only when the filter is selective, meaning it returns a small share of the object's records. As a rough guide, a custom index is used when the filter matches under about 10% of the first million records. The limit for standard indexes is about 30%. These thresholds are approximate and Salesforce can change them. For the exact current numbers, check the documentation on query selectivity.
Because unique values are one-per-record, a filter on a unique field is selective by nature.
SELECT Id, Name FROM Account WHERE ERP_Id__c = 'ERP-1001'On a large object, a query that does not use an index can hit the "non-selective query" error in triggers and slow the page loading it. These filters usually defeat an index:
- Negative operators, such as
!=orNOT IN. - A leading wildcard, such as
LIKE '%1001'. - Comparing a field to null in many cases.
- Filtering on a field that cannot be indexed, such as a Long Text Area.
Choosing between them
- Use unique alone when a business rule forbids duplicates but no outside system is involved, such as a badge number.
- Use external ID alone when the source system's values may legitimately repeat or the data is messy. Remember that upsert fails when it finds several matches.
- Use both for a key shared with another system. This is the usual choice.
- Use an Auto Number field with External ID when Salesforce is the system that generates the identifier.
Exercise
An integration upserts Account records by a field called ERPId_c, which is marked External ID but not Unique. Two accounts already hold the value ERP-2000. What happens when a row with ERP-2000 is upserted, and what is the fix?
Show answer
The upsert fails for that row, because Salesforce finds more than one match and cannot choose which record to update. The fix is to remove or merge the duplicate accounts, then mark ERPId_c as Unique so the problem cannot return.
Exercise
Why is WHERE ERP_Id__c = 'ERP-1001' fast on an object with millions of records, while WHERE ERP_Id__c LIKE '%1001' is not?
Show answer
Unique and external ID fields are indexed, and an equality filter on a unique value returns one row, so the optimizer can use the index. A leading wildcard cannot use an index, so Salesforce must scan the records.