Data Manipulation Language (DML) in Salesforce Apex – Complete Guide with Examples

In Salesforce, to retrieve the data from the Salesforce org, we use a SOQL query. However, when performing data operations (such as Insert, Update, and Delete) on Salesforce records, we use DML (Data Manipulation Language) in Salesforce Apex.

Working with data is one of the most important tasks. Every business application needs to create, update, or delete records in the database.

In Salesforce, we use Data Manipulation Language (DML) in Apex to perform these operations. DML allows developers to interact with the Salesforce database and manage records efficiently.

If you are learning Apex, understanding DML is very important because it is used in almost every real-time project.

Whether you are building automation, writing triggers, or developing integrations, you will use DML operations. Apex is a powerful programming language that runs on the Salesforce platform and enables developers to build business logic directly in the database.

In this tutorial, we will learn about Data Manipulation Language (DML) in Salesforce Apex. Additionally, I will explain the DML operations that can be performed and how to execute them within Apex classes.

What is Data Manipulation Language (DML) in Salesforce Apex?

DML stands for Data Manipulation Language, which performs operations on records, such as inserting new records, updating existing records, deleting records, and restoring deleted records. It helps developers manage data inside the Salesforce database.

DML is used to update data in Salesforce. For example, when a user creates a new account, updates a contact, or deletes a record, DML operations are executed behind the scenes.

These operations can be performed on a single record or multiple records at once.

DML allows us to perform operations on a single sObject record or in bulk on a list of records simultaneously. DML is a very important part of Apex for updating Salesforce databases.

DML operations are very fast and efficient because they are optimized for the Salesforce multi-tenant environment. This means multiple users and organizations can use the same platform without affecting performance.

Why Do We Use DML in Apex?

DML is used whenever we need to modify data in Salesforce. It is different from SOQL (Salesforce Object Query Language), which is used to retrieve data. While SOQL is used to read data, DML is used to write or modify data.

In real-time projects, DML is used in many scenarios, such as:

  • Creating new customer records
  • Updating account information
  • Deleting duplicate records
  • Restoring accidentally deleted data

Without DML, these operations cannot be performed programmatically. This is why DML is considered a core concept in Salesforce development.

Syntax: Using DML Operation in Apex

DML_Operation List or sObject;
  • DML_Operation: Here, we need to specify which operation we want to perform. For example, DELETE or UNDELETE data in the Salesforce database.
  • List: Provide a list collection variable name where you have stored data on which you want to perform the DML operation.
  • sObject: Provide the standard or custom object name on which you want to perform the DML operation.

INSERT DML Operation in Salesforce Apex

The insert operation adds new records to the Salesforce database. Using the Insert DML statement, we can create records of any standard or custom object.

Example: Create New sObject Record Using DML in Apex

In the example below, I explain how to use the INSERT DML operation to create a new record for an sObject.

The Insert operation creates new records in Salesforce. Whenever you want to add data to the database, you use the insert statement.

public class Demo {   
    public void UseDML() {
                   
        Account acc = new Account(Name = 'DML Account');                        
        INSERT acc;
    }
} 

In the code above, we created an sObject(Account) instance and set the name field to a value.

After that, write the INSERT DML statement and provide the object instance to create or insert the account record in Salesforce.

In the image below, you can see that the account record has been successfully created.

DML Operations in Salesforce Apex

Example: Create Multiple New Records Using DML in Apex

To create multiple records using the INSERT DML operation, we need to use a list collection.

In the code below, we first declared a list to store the records we want to insert, allowing us to perform a single INSERT operation.

After that, we need to create an sObject instance to add values to the field or to create the record. After providing values, we need to add that instance to the list that we created.

We need to create instances based on the number of records we need to create.

public class Demo {   
    public void UseDML() {
                   
       List<Contact> contactList = new List<Contact>();

        Contact con1 =  new Contact();
        con1.FirstName = 'First';
        con1.LastName = 'Contact';

        contactList.add (con1);
        
        Contact con2 = new Contact();
        con2.FirstName = 'Second';
        con2.LastName = 'Contact';

        contactList.add (con2);

        INSERT contactList;

    }
} 

In the image below, you can see the contacts have been successfully created using the name we provided.

INSERT DML Operation in Apex

UPDATE DML Operation in Salesforce Apex

The Update operation is used to modify existing records in Salesforce. Before updating, you need to retrieve the record using SOQL.

Example: Use the UPDATE DML Operation in Apex

In this example, we query the account that we inserted in the previous insert operation example and update its name and other fields.

In the image below, you can see we created an account record named ‘DML Account’ using the INSERT operation in the above example.

Now we will update the account name, account priority, and rating fields using the UPDATE DML operation.

UPDATE DML Operation in Salesforce Apex

In the Apex class below, we first fetched the account record that we want to update. Then, we updated the fields and used the UPDATE DML statement to update the specific record in the Salesforce database.

After that, we retrieved the updated account information using another SOQL query and displayed it using the debug method.

public class Demo {   
    public void UseDML() {
                   
        Account accountRecord  = [ Select Id, Name from Account where Name = 'DML 
                                                                         Account' LIMIT 1 ];

        accountRecord.Name = 'Updated DML Account';                                                      
        accountRecord.Account_Priority__c = 'High';
        accountRecord.Ratings_0_5__c = 4;

        UPDATE  accountRecord; 
        
        Account acctRecord =[ Select Id, Name from Account where Name = 'Updated DML 
                                                              Account' LIMIT 1 ];
        system.debug( 'account afterUpdate::: ' +acctRecord );        
    }
}

In the image below, you can see that the account record has been updated with the values provided in the Apex code.

Data Manipulation Language(DML) in Salesforce Apex

MERGE DML Operation in Salesforce Apex

The merge statement in Apex is used to combine duplicate records in the Salesforce Org and can only combine records for the leads, accounts, and contacts objects.

While merging records, one record will serve as the main (master) record, and the others will be merged into it.

Here is a very important thing: you cannot merge records that have different owners. If you have modify all data permissions, you can merge records from different owners. Also, be very careful when using merge, as it deletes duplicate records.

Example: Merge Records Using DML Statement in Apex

In this example, we will merge the Contact records using the merge statement, keeping the primary Contact and moving the other Contact records.

Now, let’s first check the duplicate contact records in the Contact object.

As you can see, we have three duplicate contacts, each with different values in the fields. After merging the records, the master record retains the data, and the other two contacts will get merged into it.

Merge Statement in Salesforce Apex

In the Apex code below, we first need to find up to three Contact records with the last name “Joy.” Of these, the first Contact in the list is selected as the master record and will be retained after the merge.

The remaining one or two Contacts are considered duplicates and are added to a separate list collection to be merged.

Then, the merge statement is used to combine the duplicate Contacts into the master record. As a result, the master Contact retains the same data, while duplicates are deleted, and all related data, such as activities and cases, are transferred to the master record.

public class ContactMerger {
    
    public static void mergeDuplicateContacts() {
        List<Contact> contactList = [ SELECT Id, FirstName, LastName FROM Contact WHERE LastName = 'Joy' LIMIT 3 ];

        if (contactList.size() < 2) {
            System.debug( 'Not enough duplicate contacts found to perform merge.' );
            return;
        }

        Contact masterContact = contactList[0];

        List<Contact> contactsToMerge = new List<Contact>();

              for (Integer i = 1; i < contactList.size(); i++) {
                    contactsToMerge.add(contactList[i]);
          }

        try {
            merge masterContact contactsToMerge;

            System.debug ('Merge completed successfully.');
        } catch (Exception e) { 

            System.debug( 'Error during merge: ' + e.getMessage());
        }
    }
}

Now, let’s execute the above class to open an anonymous window.

Execute Apex class in Salesforce

As we can see, the output of the duplicate contact record is deleted and merged with the primary contact record.

Merge Contacts in Salesforce

In this way, we can use a merge DML statement in Apex to combine the records in Salesforce.

Example: Merge Records Using Database.Merge() Method in Salesforce Apex

In Salesforce Apex, the Database.merge() method provides an alternative to the standard merge statement for handling errors more efficiently.

In this example, we will merge the two account records into a single record using the Database.merge() method.

public class AccountMerger {

    public static void mergeAccounts(Id primaryAccountId, Id duplicateAccountId) {
        try {
            Account primaryAccount = [SELECT Id, Name, Industry, Phone FROM Account WHERE Id = :primaryAccountId LIMIT 1];
            Account duplicateAccount = [SELECT Id, Name, Industry, Phone FROM Account WHERE Id = :duplicateAccountId LIMIT 1];

            Database.SaveResult mergeResult = Database.merge(primaryAccount, new List<Account>{duplicateAccount}, false);

            if (mergeResult.isSuccess()) {
                System.debug('Merge successful: Primary Account ID ' + primaryAccountId + ' now includes data from Duplicate Account ID ' + duplicateAccountId);
            } else {
                for (Database.Error error : mergeResult.getErrors()) {
                    System.debug('Merge failed due to error: ' + error.getMessage());
                }
            }

        } catch (Exception e) {
            System.debug('An unexpected error occurred during the merge: ' + e.getMessage());
        }
    }
}

Call the method with an anonymous code:

Id primaryAccountId = '0015i00000lU1htAAC'; 
Id duplicateAccountId = '001J3000007zBBkIAM'; 
AccountMerger.mergeAccounts(primaryAccountId, duplicateAccountId);

Output:

Merge Records in Salesforce Apex using database.merge method

In the output, we can see that the duplicate account is merged with the primary account, along with the related fields.

This way, we can merge records in Salesforce Apex using the Database.merge() method.

Difference Between Merge & Database.Merge Methods in Apex

The working of both the methods merge, and database.merge are efficient to merge records in Salesforce using Apex. Now, we will see the differences between these two methods.

Merge method: The Salesforce Apex merge statement is suitable for simple merge operations and is best suited to scenarios requiring minimal customization and error handling.

It throws exceptions directly if any errors occur during the merge, so the process halts if an error is encountered.

This feature is beneficial for simple merges that involve up to three records and do not require advanced error handling.

Database.merge(): This method provides greater control and flexibility, particularly with error handling. Instead of throwing exceptions directly, it captures errors in a MergeResult object, allowing us to review and handle issues more efficiently without interrupting the execution flow.

This method is helpful in complex scenarios where error handling is critical. It supports merging up to 3 records while ensuring execution continues even when errors occur, enhancing the user experience.

DELETE DML Operation in Apex

Below, I will explain what the Delete and Undelete DML statements are in Salesforce Apex and how to use them to remove unnecessary records and restore deleted records.

Delete operations are performed on the existing records in the Salesforce database. Deleted records are not permanently deleted from Salesforce.

After deleting the records, they are stored in the recycle bin for 15 days, after which they can be restored within the same timeframe.

Now, let’s consider a scenario where I want to delete the account named ‘Updated DML Account‘.

Before that, you can see that when we search for an account in the global search, it appears in the account object.

DELETE DML Operation in Apex

In the Apex code below, we first retrieve the account record that we want to delete. Then, using the DELETE DML operation, we will delete that record.

After that, we declared list collection to store the account records we deleted. If an account is deleted, this list will be empty; otherwise, it will contain some records.

Then, using an if condition, we checked whether the list is empty, the account gets successfully deleted.

public class Demo {   
    public void UseDML() {
        
        Account accDelete =[ Select Id, Name from Account where Name = 'Updated DML Account' LIMIT 1 ];

        DELETE accDelete;
        
        List<Account> accList = new List<Account>();
        accList = [ Select Id, Name from Account where Name = 'Updated DML Account' LIMIT 1 ];
        
        if (accList.size() == 0){
              system.debug( 'account does not exist' );
        }
         else{
              system.debug( 'account existed' );
           }
     }
}

In the Execution Log, the result ‘account does not exist’ means the record was successfully deleted.

Salesforce Apex DML Operations

Additionally, if you search again for the deleted account record name in the global search, it will not appear in the search results.

Use DELETE DML Statement in Apex

In this way, we can use the DELETE DML operation in Salesforce Apex to delete the records.

UNDELETE DML Operation in Apex

If you accidentally delete a record in Salesforce, you can restore it using the undelete operation in Salesforce Apex, which is designed to recover deleted records.

When you delete records, they are stored in the Recycle Bin for 15 days. After 15 days, they are permanently deleted from Salesforce.

To query deleted records from the recycle bin, we must use the ALL ROWS parameter in the SOQL query.

For example, we want to retrieve the account records we deleted in the above delete operation example. To restore the deleted account, we need to use the UNDELETE DML operation in Apex.

In the DELETE DML operation above, we deleted the ‘Updated DML Account’. Now, we want to restore this account using the UNDELETE DML operation.

In the Apex code below, we first retrieve the account record that we want to restore. Additionally, we need to use the ALL ROWS clause to restore all deleted fields. Then, using the UNDELETE DML operation, we restored that record.

public class Demo {   
    public void UseDML() {
        
        Account accRestore = [ select Id, Name from Account where Name = 'Updated DML Account' ALL ROWS ];

        UNDELETE accRestore;
        
        Account accn = [ select Id, Name from Account where Name = 'Updated DML Account' ];
        system.debug( 'restored account record :  ' +accn );
    }
}

In the Execution Log, the result displayed the account information that had been restored.

UNDELETE DML Operation in Apex

Again, as you search for the restored account name in the global search, it will appear in the search results.

DELETE DML Operation in Apex

In this way, we can use the UNDELETE DML operation in Salesforce Apex to restore the records.

Conclusion

Data Manipulation Language (DML) is a core concept in Salesforce Apex that allows developers to manage data efficiently. It is used in almost every Salesforce application to perform operations like insert, update, delete, and undelete.

Understanding DML with real-time examples, best practices, and limitations is crucial for building scalable, efficient applications. If you master DML, you will be able to handle most real-world Salesforce development scenarios easily.

You may like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.