upsert()

Creates new records and updates existing records; uses a custom field to determine the presence of existing records. 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. You can process records for one more than object type in an create() or update() call, but all records must have the same object type in an upsert() call.

Note

Starting with API version 15.0, if you specify a value for a field that contains a string, and the value is too big for the field, the call fails and an error is returned. In previous versions of the API the value was truncated and the call succeeded. If you wish to keep the old behavior with versions 15.0 and later, use the AllowFieldTruncationHeader SOAP header.

Syntax

UpsertResult[] = connection.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 record or update an existing record. On standard objects, this call can use the name of any field with the idLookup field property instead of the external ID.

Note
External ID fields cannot be used with merge().

For more information about adding custom fields, including external ID 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 a record for 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 a record for 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 record or update an existing one:

Rollback on Error

The AllOrNoneHeader header allows you to roll back all changes unless all records are processed successfully. This header is available in API version 20.0 and later. The default behavior is to allow partial success of a call: records without errors are committed, while records with errors are marked as failed in the call results.

Automatic Subscriptions for Chatter Feeds

When you create a new record, the owner is automatically subscribed to the record, meaning they follow the record in Chatter and see changes to that record in their Chatter feed on the Home tab. When you update the owner of a record, the new owner is automatically subscribed to the record. The previous owner is not automatically unsubscribed. This means that the new and previous owners both see any changes to the record in their news feed. The subscription occurs unless the user has selected the Stop automatically following records checkbox in Your Name | Setup | My Chatter Settings | My Feeds.

A user can subscribe to a record so that changes to the record are displayed in the Chatter feed on the user's home page, which is a useful way to stay up-to-date with changes made to records in Salesforce. Feeds are available in API version 18.0 and later.

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.

public void upsertForeignKeySample()
{
  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(upsertParentAccountRef);
  //Set the external ID for the Opportunity
  upsertOpportunity.set_SAP1_OPPID__c("SAP222222");
  UpsertResult[] upsertResults = binding.upsert("SAP1_OPPID__c",
            new SObject[] {upsertOpportunity});
  // check results and do more processing after the upsert call ...
}

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 upsertRecords() {
    SObject[] upserts = new Account[2];
    // This account is assumed to exist.
    // Could be from the results of a retrieve or query call.
    Account upsertAccount = new Account();
    upsertAccount.setWebsite("http://www.example.com");
    // A custom field External_ID__c is used
    // for "External ID" on Upsert
    upsertAccount.setExternal_ID__c("1111111111");
    upserts[0] = upsertAccount;
    // This account is 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 =
          connection.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("Account ID: " + result.getId());
        } else {
          System.out.println("The Upsert failed because: " + 
              result.getErrors()[0].getMessage());
        }
      }
    } catch (ConnectionException ce) {
      ce.printStackTrace();
    }
  }

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 records (maximum of 200) to create or update.

Response

UpsertResult[]

Faults

InvalidSObjectFault

UnexpectedErrorFault

© Copyright 2000–2012 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.