upsert()

Creates new objects and updates existing objects; uses a custom field to determine the presence of existing objects. In most cases, we recommend that you use upsert instead of create() to avoid creating unwanted duplicate records (idempotent). Available in the API version 7.0 and later.

Syntax

UpsertResult[] = sfdc.upsert(String externalIdFieldName, sObject[] sObjects);

Usage

Upsert is a merging of the words insert and update. This call is available for objects if the object has an external ID field or a field with the idLookup field property.

On custom objects, this call uses an indexed custom field called an external ID to determine whether to create a new object or update an existing object. On standard objects, this call can use the name of any field with the idLookup field property instead of the external ID.

For more information about custom fields designated as external ID fields, see Required Fields. For more information about adding custom fields to objects, see the “Adding Fields” topic in the Salesforce online help.

Using this call can dramatically reduce how many calls you need to make, particularly when:

If you are upserting an object that has a custom field with both the External ID and Unique attributes selected (a unique index), you do not need any special permissions, because the Unique attribute prevents the creation of duplicates. If you are upserting an object that has the External ID attribute selected but not the Unique attribute selected, (a non-unique index) your client application must have the permission “View All Data” to execute this call. Having this permission prevents the client application from using upsert() to insert an accidental duplicate record because it couldn’t see that the record existed.

Note
Matching by external ID is case-insensitive only if the external ID field has the Unique attribute and the Treat "ABC" and "abc" as duplicate values (case insensitive)) option selected. These options are selected in the Salesforce user interface during field creation. If this is the case, “ABC123” is matched with “abc123.” Before performing an operation, if you have external ID fields without the case-insensitive option selected, review your external IDs for any values that would be matched if case was not considered. If such values exist, you may want to modify them to make them unique, or select the case-sensitive option for your external ID fields. For more information about field attributes, see "Custom Field Attributes" in the Salesforce online help.

How Upsert Chooses to update() or create()

Upsert uses the external ID to determine whether it should create a new object or update an existing one:

  • If the external ID is not matched, then a new object is created.
  • If the external ID is matched once, then the existing object is updated.
  • If the external ID is matched multiple times, then an error is reported.
  • When batch updating multiple objects where the external ID is the same for two or more objects in your batch call, those records will be marked as errors in the UpsertResult. The objects will be neither created or updated.

upsert() and Foreign Keys

You can use external ID fields as a foreign key, allowing you to access records in a single step instead of querying a record to get the ID first. To do this, specify the foreign key name and the external ID field value.

The following example upserts an Opportunity. The Opportunity references an Account. Rather than specify the account ID, which would require a separate query to obtain, we specify an external ID for the account, in this example the External_SAP1_ACCTID__c custom field.

Opportunity upsertOpportunity = new Opportunity();
upsertOpportunity.setStageName("Prospecting");
//To indicate the reference, attach an Account object, 
//which has only the external ID field specified.
Account upsertParentAccountRef = new Account();
upsertParentAccountRef.setExternal_SAP1_ACCTID__c("SAP111111"); 
upsertOpportunity.setAccount(upsertParentAccount);
//Set the external ID for the Opportunity
upsertOpportunity.set_SAP1_OPPID__c("SAP222222"); 
UpsertResult[] upsertResults = binding.upsert("SAP1_OPPID__c", 
            new SObject[] {upsertOpportunity});

upsert() and Polymorphic Foreign Keys

A polymorphic key is an ID that can refer to more than one type of object as a parent. For example, the OwnerId field on the Case object can reference either a User or a Group. Similarly, the WhoID field on the Task object can reference either a Contact or a Lead.

With the Enterprise WSDL, such polymorphic foreign key fields are defined as a Name sObject type, so it is not possible to pass in the correct sObject in an upsert() call. However, with the Partner WSDL all foreign key fields—including polymorphic ones—are of type sObject, which allows upsert() calls on such fields.

Sample Code—Java

The following sample is for an upsert specifying the Salesforce object ID.

public void upsertAccountSample()
{
  // Create an array of SObjects to send to the upsert method
  SObject[] upserts = new Account[2];
  // This account is assumed to be existing.
  // Could be from the results of a retrieve or query call.
  Account upsertAccount = new Account();
  upsertAccount.setWebsite("http://www.website.com");
  // A custom field "External_Id" is used for "External ID" on Upsert
  upsertAccount.setExternal_Id__c("1111111111");
  upserts[0] = upsertAccount;
  // This account is meant to be new
  Account upsertAccount2 = new Account();
  upsertAccount2 = new Account();
  upsertAccount2.setName("My Company, Inc");
  upsertAccount2.setExternal_Id__c("2222222222");
  upserts[1] = upsertAccount2;
  try {
    // Invoke the upsert call and save the results.
    // Use External_Id custom field for matching records
    UpsertResult[] upsertResults = binding.upsert("External_Id__c", upserts);
    for (UpsertResult result : upsertResults) {
      if (result.isSuccess()) {
        System.out.println("\nUpsert succeeded.");
        System.out.println((result.isCreated() ? "Insert" : "Update") + 
                           " was performed.");         
        System.out.println("The Account id: " + result.getIds(0).toString());
      } else {
        System.out.println("The Upsert failed because: " + 
                           result.getErrors(0).getMessage());
      }
    }
  } catch (RemoteException ex) {
    System.out.println("An unexpected error has occurred." + ex.getMessage());
  }
  getUserInput("\nPress the RETURN key to continue...");
}

Sample Code—C#

The following sample is for an upsert specifying the Salesforce object ID (not the foreign key).

private void upsertSample() 
{
   if (!loggedIn) {
      if (!login())return;
   }

   //First, create a contact using the upsert call.  The contact must have a custom
   //field that is designated as an external id. In this case it's called ExternalId__c
   sforce.Contact[] contact = new Contact[1];
   contact[0] = new sforce.Contact();
   contact[0].LastName = "External_Id";
   contact[0].FirstName = "Test"; 
   contact[0].ExternalId__c = "01010101";

   sforce.UpsertResult ur = binding.upsert("ExternalId__c", contact)[0];

   if (ur.success)
   { //Check out the created flag
      Console.WriteLine("Value of created flag is: " + ur.created);
   }
   else
   {  //Report an error
      Console.WriteLine("Error: \n" + ur.errors[0].message);
      return;
   }

   //Now, we can call the upsert again changing a value.
   contact[0].FirstName = "Joe";
   contact[0].LastName = "Sampson";

   ur = binding.upsert("ExternalId__c", contact)[0];

   if (ur.success)
   {  //Check out the create flag, should be false now
      Console.WriteLine("Value of created flag is: " + ur.created);
   } 
   else 
   {  //Report an error
      Console.WriteLine("Error: \n" + ur.errors[0].message);
      return;
   }
}

Arguments

Name Type Description
ExternalIDFieldName string Contains the name of the field on this object with the external ID field attribute for custom objects or the idLookup field property for standard objects. The idLookup field property is usually on a field that is the object's ID field or name field, but there are exceptions, so check for the presence of the property in the object you wish to upsert().
sObjects sObject[] Array of one or more objects (maximum of 200) to create or update.

Response

UpsertResult[]

Faults

InvalidSObjectFault

UnexpectedErrorFault

See Also:
create()
update()
API Call Basics
© Copyright 2000-2008 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.