I have a question about looping over a list created from a SOQL query on Account. I need to find Accounts in the list that match on certain values and then update the matching Accounts. So far this is what I have come up with.

My question is, how do I compare the values from the list so I can find all of the accounts that have the same contact name, billing state and phone number? I need to update them so that the first account would be the parent account, and every other account that meets the criteria would be a child account. I have a multi-location checkbox that I will use to tie the accounts together, along with the parent account Id. Any help would be greatly appreciated.

Id rtype = Schema.SObjectType.Account.getRecordtypeInfosByname().get('Business').getRecordTypeId();
    for (List<Account> accList = [SELECT Name, (SELECT Id, Name, LastName from Contacts), AccountNumber, BillingState, Phone, Id 
    FROM Account Where RecordTypeId !=:rtype Order by Day_Revenue__c DESC]){
        System.debug('acclist ' + JSON.serialize(accList));
        List<Account> accountsToUpdate = new List<Account>();
        for(Account acc:accList){
           List<Contact> cList = acc.Contacts;
           for(Contact c:cList){
            // get the contact from the account
            // compare the values for each account in the list

      upsert accountsToUpdate;

  • You're trying to ensure that the Account and Contact have consistent data? – EricSSH Oct 11 '18 at 20:32
  • EricSSH, no I have a lot of accounts that are multi location and I need to link them as such and add a parent account. based off of the contact name, state and phone number. so we only call them once. if there is a parent account the child won't be called. – user61039 Oct 11 '18 at 20:42

Instead of trying to find matches by looking at Contact Name, State, and Phone Number separately, concatenate their values into one "pattern" and use it to find Accounts with the same pattern:

List<Account> accList = [SELECT Name, (SELECT Id, Name, LastName from Contacts ORDER BY LastName ASC), AccountNumber, BillingState, Phone, Id FROM Account WHERE ....];
Map<String, List<Account>> pattern_to_Accounts = new Map<String, List<Account>>();

for(Account acct : accList){

    String keyPattern = acct.BillingState + acct.Phone;
    if(acct.Contacts.size() > 0){
        keyPattern += acct.Contacts[0].Name;


    } else {
        pattern_to_Accounts.put(keyPattern, new List<Account>{acct});

// loop through the lists of matching accounts
for(List<Account> accts : pattern_to_Accounts.values()){

    if(accts.size() > 1){
        // do your linking magic here


This isn't a perfect way of matching up Accounts, but it should give you a start.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.