Salesforce Performance - Updating SObjects

A tip for updating SObjects:

If you already know the Id, you don't need to query it first. For instance, if you have a contact object and want to update the corresponding Account, you simply set the Id as in the example below.

// assume we have a contact called myContact
Account acct = new Account();
acct.Id = myContact.Account;
acct.Fax= '123-456-7890';
update acct;
                    

This will perform better and reduce the Queries, Query rows, and cpu time that apply to limits.

It's not necessary to select the account first.

Also note: you cannot access the value of the field of an SObject without querying for that field; however, you can set the field.

This will give a runtime error:

Account acct = [SELECT Name FROM Account WHERE Id =:myContact.Account];
String fax = acct.Fax;
                    

This will not give a runtime error:

Account acct = [SELECT Name FROM Account WHERE Id =:myContact.Account];
acct.Fax = '123-456-7890';
                    

 

 

© 2001 – 2023 Object Factory Inc
marker marker marker marker marker