1

Good morning.

Database.update (fields , allOrNothing)
Database.upsert (fields, externalId, allOrNothing)

I need help to understand why the second parameter "externalId" is not necessary on the update method?

Thanks for reading !

1 Answer 1

4

Records sent to update must have the Id field populated (at the very least) to be able to perform the DML.

upsert can take a mix of new records (without an Id) and existing records (with an Id). Behind the scenes, it'll perform an insert on the new records, and an update on the existing records. In the past, I believe the "gotcha" was that Salesforce goes through the list of records linearly and performs a dml operation when:

  • they hit the end of the list
  • they find a record that requires the opposite operation that they're currently gathering records to run

Though I admit I might be getting this confused with what happens when you perform DML on a List<SObject> with multiple object types in it...

When I tried to recreate that (upsert doing dml as it linearly scanned the list), it appears that Salesforce is smart enough to group the new records together and the existing records together before performing the subsequent DML.

The optional externalId argument tells Salesforce to look at the field you specify (one where the "external Id" checkbox is checked) when making its decision about whether a record is new or existing.

It's useful for when records originated from an external system, and allows you to update existing records without knowing the Salesforce record's Id. The main "gotchas" here are:

  • The list you're upserting cannot have the same value in your external Id field appear in two records (basically the same as with normal Ids)
  • The existing records stored in Salesforce can't have 2 records with the same external Id (Salesforce can't choose which one to update)
1
  • Thanks for such a valuable response Derek !
    – LatDu
    Nov 26, 2021 at 14:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .