function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SureshSuresh 

Upsert usage

Hi All,

At what situation are we going to use upsert operation.

Regards,
Suresh.
Best Answer chosen by Suresh
pconpcon
It is also worth noting that when you do an upsert they are split into two different transactions for your triggers.  So your trigger will be executed once for the objects that are being inserted, and once for the objects that are being updated.

I've used upserts before when doing something like mass creating a child object on the update of it's parent and we only want one instance of the record per parent.  So we'd query for all of the children and then update the list with the new values.  If the list didn't contain one for the parent object then we'd create a new instance.  And instead of having to have an updateList and an insertList you can simply call upsert on a single list object.

All Answers

Nishant SharmaNishant Sharma
When your have set of records, few of them needs to be inserted and few should be updated.

upsert lstObject;

so the records having id in lstObject will be updated and the one without id will be inserted.
pconpcon
It is also worth noting that when you do an upsert they are split into two different transactions for your triggers.  So your trigger will be executed once for the objects that are being inserted, and once for the objects that are being updated.

I've used upserts before when doing something like mass creating a child object on the update of it's parent and we only want one instance of the record per parent.  So we'd query for all of the children and then update the list with the new values.  If the list didn't contain one for the parent object then we'd create a new instance.  And instead of having to have an updateList and an insertList you can simply call upsert on a single list object.
This was selected as the best answer