"Upsert" just inserts new records from JSON, but not updates existing.

It's my code:

public class myClass {

@future (callout = true)
public static void getCallout(){

    Http http = new Http();
    HttpRequest request = new HttpRequest();
    HttpResponse response = http.send(request);

    if (response.getStatusCode() == 200){
        List<Object> jsonList = (List<Object>) JSON.deserializeUntyped(response.getBody());
        List<Product2> productList = new List<Product2>();

        for(Object o : jsonList){
            Map<String, Object> results = (Map<String, Object>) o;
            Product2 prod = new Product2();
            prod.Cost__c = Integer.valueOf(results.get('cost'));
            prod.Warehouse_Key__c = String.valueOf(results.get('sku'));  //My key to check a record
        if(productList != null){
            upsert productList;  //It just inserted, but not update existing records if I change them

What am I doing wrong?

1 Answer 1


To make upsert update records you have to specify either record Id or External Id. When neither is specified, Salesforce treats the record as new and inserts it.

Example with record Id:

Product2 prod = new Product2();
prod.Id = '<salesforce id here>';

upsert prod;

Example with record External Id:

Product2 prod = new Product2();
prod.Warehouse_Key__c = '<extenral id here>';

upsert prod Warehouse_Key__c; // this is important since it specifies the field which Salesforce will use to match the record.

Upserting Records

To determine whether a record already exists, the upsert statement or Database method uses the record’s ID as the key to match records, a custom external ID field, or a standard field with the idLookup attribute set to true.

  • Even if it's custom field? prod.Warehouse_Key__c Commented Aug 3, 2018 at 12:50
  • Yes, basically all External Id fields are custom fields.
    – Eduard
    Commented Aug 3, 2018 at 12:58
  • 1
    Few exceptions like externalID on Product object Commented Aug 3, 2018 at 15:44

You must log in to answer this question.

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