Advanced DML Operations: Upsert and Merge
Sometimes we do not know whether a record already exists or not. Instead of writing separate logic to insert or update, we can use the upsert operation which will provide in-built to check which operation to perform insert or update.
Upsert Operation
Upsert is a combination of insert and update. It checks whether a record exists (usually based on an external or Salesforce ID) and performs an insert if it is not present or an update if it already exists in the system.
public class SimpleDML {
public static void upsertAccount(Account acc) {
// Upsert the Account record. If it exists, update it; if not, insert a new record.
upsert acc;
System.debug('Upserted Account with Id: ' + acc.Id);
}
}
In the above example, upsert command handles both creating and updating records based on whether the record’s identifier is present or not.
Merge Operation
When we have duplicate records and want to combine them into one, the merge operation comes into play. Merge operation is very useful when cleaning up data by combining duplicate records and keeping correct records in the system.
public class SimpleDML {
public static void mergeAccounts(Account masterAccount, Account duplicateAccount) {
// Merge duplicateAccount into masterAccount
merge masterAccount duplicateAccount;
System.debug('Merged duplicate account into master account: ' + masterAccount.Id);
}
}
In this code/example, two account records are merged, with the duplicate being combined into the master record. Note that merge operations work only on records of the same object type.