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
Parteek Goyal 3Parteek Goyal 3 

How to use upsert in apex class

Hi All,
How to use upsert method in apex class.
Best Answer chosen by Parteek Goyal 3
Chidambar ReddyChidambar Reddy
Account[] acctsList = [SELECT Id, Name, BillingCity
                        FROM Account WHERE BillingCity = 'Bombay'];
for (Account a : acctsList) {
    a.BillingCity = 'Mumbai';
}
Account newAcct = new Account(Name = 'Acme', BillingCity = 'San Francisco');
acctsList.add(newAcct);
try {
    upsert acctsList;
} catch (DmlException e) {
    // Process exception here
}

Here, newAcct will be inserted and old accounts in acctsList will get updated 
https://developer.salesforce.com/trailhead/apex_database/apex_database_dml

All Answers

Cloud Jedi SolutionsCloud Jedi Solutions
Here are some sample code that you can use to use the upsert command:
https://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_dml_examples_upsert.htm
http://www.salesforce.com/us/developer/docs/dbcom_apex/Content/apex_dml_upsert.htm
 
Chidambar ReddyChidambar Reddy
Hi Parteek,

You can follow above links to know about upsert,

and upsert is very useful when you are working with 'External id', which means you can insert/update records based on 'External Id' fields (email, text, etc which are marked as external id), though you have no salesforce Id.
Parteek Goyal 3Parteek Goyal 3
Hi Chidambar Reddy,

Thanks for your help...
I am getting you what you want to say. But i don't have any idea how to do this. 
Lets suppose i want to use upsert with Account Object, then how to do this.
Please explain with example.
Chidambar ReddyChidambar Reddy
Account[] acctsList = [SELECT Id, Name, BillingCity
                        FROM Account WHERE BillingCity = 'Bombay'];
for (Account a : acctsList) {
    a.BillingCity = 'Mumbai';
}
Account newAcct = new Account(Name = 'Acme', BillingCity = 'San Francisco');
acctsList.add(newAcct);
try {
    upsert acctsList;
} catch (DmlException e) {
    // Process exception here
}

Here, newAcct will be inserted and old accounts in acctsList will get updated 
https://developer.salesforce.com/trailhead/apex_database/apex_database_dml
This was selected as the best answer