I want to use external id to reference a parent record on a lookup field. The problem is if this external id can't target that record, I just want to leave that lookup field a null.

Contact ct = new Contact(LastName = 'Smith', 
                         FirstName = 'John', 
                         Account = new Account(ExternalId__c = 'xxxxxxx')); 

Assuming that ExternalId__c from Account sObject is set as EXTERNAL ID. I want to upsert ct no matter Account field has a value or not. What should I do with this?

I can also do it in a complex way but that will make no sense to use external id.

Contact ct = new Contact(LastName = 'Smith',FirstName = 'John');
List<Account> accList = [select id from Account where externalId__c = 'xxxxxxx'];
if(accList.size()==1){ct.Account = accList[0].id}
insert ct;
  • Are you reading the ext Id value from somewhere? Passed in as a param or something? Where does the value 'xxxxxxx' come from?
    – pchittum
    Apr 4, 2016 at 9:47

1 Answer 1


Assuming that the External Id value is coming from somewhere, and not just hard coded, I'm going to make up a scenario...you are passing it in from a parameter on an invoked method. I'm going to call it extIdParam.

Without actually trying this out, I would assume if the account you passed to the Account field of Contact just reflected the state you want it would be ok. (Either a null account field, or one with the external Id you want).

I would try something like this:

Account acctFieldVal = extIdParam == null ? null : new Account(ExternalId__c = extIdParam));

I like to use the ternary operator for problems like this. It is clean and simple. I'm assuming that whatever is passing in the value that will be used for the external Id is initialized to null, but depending on where that data comes from or what form it is in (empty string, for instance) you may need to fiddle with the logic here.

Then pass acctFieldVal to the field when you instantiate the Contact.

Contact ct = new Contact(LastName = 'Smith', 
                     FirstName = 'John', 
                     Account = acctFieldVal);

You will either have the null account (in which case no Account associate is made) or the in-memory instantiated version with the external Id.

I did this free hand, if I can test it out later, I will.

  • Thanks Peter, what I thought is to test if I can find the record by making up an external id. I've modified my question a little bit.
    – Joey Yao
    Apr 5, 2016 at 2:49

You must log in to answer this question.

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