I know that with External Id, I can upsert a record and that will Insert or Update the record base on the External Id (update if exists or insert if not) instead of the regular Id.

Is there is a way to update\ insert a record based on its external Id?

Example (Code__c is an external Id):

List<Example__c> ExampleList= [SELECT Id,Code__c,Name FROM Example__c LIMIT 1]; 
SomeObjectInstance.someLookupField__c = ExampleList[0].Code__c;

instead of:
SomeObjectInstance.someLookupField__c = ExampleList[0].Id;

What about upsert a related object based on the external Id?

For Example :

Contact con = new Contact();
con.City_Code = getCity('PKR'); // Getcity is the function below

//what should I do now with the contact? 

public static String getCity(String wsDemoCity){
    List<City__c> countryList = [
        SELECT Id,Code__c,City_Name_Eng__c FROM 
        City__c WHERE Code__c =:wsDemoCity LIMIT 1
        return countryList[0].code__c;
  • Yes, it is possible to insert or update using a external id. What how are you planning to insert or update those records? DataLoader, Integration , ... ? You can create a process to do this. Commented Nov 27, 2018 at 13:50
  • Thank you ! I updated the question' below the '---' can you please look at it again? And for your question - its via apex - webservice rest API @Carlos Naranjo
    – Salvation
    Commented Nov 27, 2018 at 14:29
  • An external id is not always unique Commented Nov 27, 2018 at 14:32

1 Answer 1


Instead of insert/update just call upset and specify the external id. The operator will handle it for you.

SomeObjectInstance.someLookupField__c = ExampleList[0].Code__c;
upsert SomeObjectInstance someLookupField__c; 

*Given that someLookupField__c is also an external id field.

Src: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_examples_upsert.htm?search_text=upsert

  • Hi @Pranay Jaiswal, I updated the wauestion below the '--' can you please look at it again?
    – Salvation
    Commented Nov 27, 2018 at 14:28
  • Is city code external id for contact? Commented Nov 27, 2018 at 14:29
  • No, the city_code is the external Id for the City object but City have a lookup relationship with Contact. (The Contact object have the lookup for city)
    – Salvation
    Commented Nov 27, 2018 at 14:32
  • No you cannot use upsert then...., upsert can only work for object that have an externalID field, as you contact doesn not have that, it wont work. You can use simple upsert. ie Upsert based on Id field. Commented Nov 27, 2018 at 14:33

You must log in to answer this question.

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