Merge Statements
Not Started

Apex supports de-duplicating records via the merge DML operation.

This operation can merge up to two records into one record. It deletes the remaining and reparent child records. The record that gets merged is referenced as the "master" record, "primary" record, or "surviving" record. Not all sObjects can be merged using this operation. It's only available to Lead, Contact, Case, and Account.

There can be a lot of complexity here. We'll focus on the core idea. Say we had a class DML_UTIL that could merge Lead records.

public class DML_UTIL { public static void mergeLeads(Lead primary, List<Lead> duplicateLeads){ if(duplicateLeads.size() <= 2){ merge primary duplicateLeads; } } }

This is an oversimplification, but it focuses on the stuff we care about in this lesson. The mergeLeads method accepts a single Lead record that will be the primary lead record. It also accepts a list of Lead records that have already been identified as duplicates. It merges the duplicates into the primary.

Code like this could call DML_UTIL to merge 2 Leads:

Lead duplicateLead = [SELECT Id FROM Lead WHERE Company = 'Apple']; Lead primaryLead = [SELECT Id FROM Lead WHERE Company = 'Apple Inc']; DML_UTIL.mergeLeads(primaryLead, new Lead[]{{duplicateLead});

The child records of the duplicate record are reparented, but their update triggers and flows will not fire. There are many other considerations to make when merging sObject records. Check out these docs for more:

Challenge

You're given a single Account record and a list of Account records. This method should merge the list of Account records into the single Account record. The list of Account records will never have more than 2 elements.