soql – Most efficient way to sync data between 2 similar objects with Apex, without a schema relationship between the objects

This is an interview question I had today. I’ve also included the best solution I can come up with for it. Is there a more efficient way of doing the same?

I did confirm I should match 2 records based on First Name + Last Name.

// There are two Custom objects in our Salesforce instance:
// Contact__c(LastName__c, FirstName__c, Phone__c) and
// Contact_Staging__c(LastName__c, FirstName__c, Phone__c).
//
// Can you write a function to perform a one-time sync of records from Contact_Staging__c into Contact__c.
//
//  1) If a record exists in Contact_Staging__c, but not in Contact__c, insert it into Contact__c.
//  2) If a record exists in Contact__c, but not in Contact_Staging__c, delete it from Contact__c.
//  3) If a record exists in both, but the phone number is different, then update the record in Contact__c.


public void SyncContacts()
{
    List<Contact__c> contactsToBeUpserted = new List<Contact__c>();
    List<Contact__c> contactsToBeDeleted = new List<Contact__c>();
    
    Map<String, Contact__c> nameToContact = new Map<String, Id>();
    Map<String, Contact_Staging__c> nameToContactStage = new Map<String, Contact_Staging__c>();

    for (Contact__c c : [SELECT LastName__c, FirstName__c, Phone__c, FullName() FROM Contact__c]) {
        nameToContact.put(c.FirstName__c + " " + c.LastName__c, c);
    }

    for (Contact_Staging__c cs : [SELECT LastName__c, FirstName__c, Phone__c FROM Contact_Staging__c]) {
        nameToContact.put(cs.FirstName__c + " " + cs.LastName__c, cs);
    }

    for (Contact_Staging__c cs : nameToContactStage.values()) {

        String fullName = cs.FirstName__c + " " + cs.LastName__c;
        Contact__c c = nameToContact.get(fullName);
        if (c != null) {
            if (c.Phone__c != cs.Phone__c) {
                c.Phone__c = cs.Phone__c;
                contactsToBeUpserted.add(c);
            } 
            nameToContact.remove(fullName);
        }
    }

    upsert contactsToBeUpserted;

    contactsToBeDeleted.addAll(nameToContact.values());
    delete contactsToBeDeleted;
}

Read more here: Source link