In-Depth Guide to Database Manipulation Language (DML) Operations in Salesforce Apex — Apex Part 7

Mohammad Usman
5 min readMar 16, 2024

--

Database Manipulation Language (DML) operations in Apex are fundamental for interacting with data within Salesforce. Apex, being a strongly-typed, object-oriented programming language, provides robust support for performing Create, Read, Update, and Delete (CRUD) operations on records in Salesforce objects. This article aims to provide a comprehensive overview of DML operations in Apex, covering basic CRUD operations, bulk DML operations, and best practices for efficient data manipulation.

Salesforce development

Table of Contents

1. Understanding DML Operations in Apex
2. Performing CRUD Operations using Apex
3. Bulk DML Operations and Best Practices
4. Error Handling and Considerations
5. Conclusion

1. Understanding DML Operations in Apex

DML operations in Apex allow developers to manipulate Salesforce records programmatically. These operations are performed using the `Database` class, which provides methods for inserting, updating, deleting, and querying records. DML operations in Apex are typically performed within transaction boundaries, ensuring data consistency and integrity.

1.1 Transaction Boundaries

In Apex, each DML operation is executed within a transaction boundary. A transaction represents a series of operations that are executed as a single unit of work. Transactions ensure that either all DML operations within the transaction are completed successfully or none of them are. This atomicity guarantees data consistency and prevents partial data modifications.

1.2 Governor Limits

Salesforce imposes governor limits on various resources, including DML operations, to ensure system stability and fair resource allocation among users. It’s crucial for developers to understand these limits and design their code accordingly to avoid hitting them. Common governor limits related to DML operations include the maximum number of records that can be processed in a single transaction and the total number of DML statements allowed per transaction.

2. Performing CRUD Operations using Apex

CRUD operations in Salesforce correspond to Create, Read, Update, and Delete actions on records. In Apex, these operations are achieved using DML statements: `insert`, `update`, `delete`, and `upsert`. Let’s explore each of these operations in detail:

2.1 Inserting Records

List<Account> accountsToInsert = new List<Account>();
accountsToInsert.add(new Account(Name=’Acme’));
accountsToInsert.add(new Account(Name=’XYZ’));
insert accountsToInsert;

The `insert` DML statement is used to create new records in Salesforce objects. In the above example, we create two Account records and insert them into the database using a single DML statement, which is more efficient than performing individual inserts.

2.2 Updating Records

Account acc = [SELECT Id, Name FROM Account WHERE Name = ‘Acme’ LIMIT 1];
acc.Name = ‘New Acme’;
update acc;

The `update` DML statement is used to modify existing records in Salesforce objects. In the above example, we retrieve an Account record with the name ‘Acme’, update its name, and then commit the changes to the database using the `update` statement.

2.3 Deleting Records

Account accToDelete = [SELECT Id FROM Account WHERE Name = ‘XYZ’ LIMIT 1];
delete accToDelete;

The `delete` DML statement is used to remove records from Salesforce objects. In the above example, we retrieve an Account record with the name ‘XYZ’ and delete it from the database using the `delete` statement.

2.4 Upserting Records

List<Account> accountsToUpsert = new List<Account>();
accountsToUpsert.add(new Account(Name=’Acme’));
accountsToUpsert.add(new Account(Name=’New XYZ’));
Database.upsert(accountsToUpsert, Account.Name);

The `upsert` DML statement is used to insert new records or update existing records based on a specified external ID field. In the above example, we upsert a list of Account records based on the `Name` field, ensuring that existing records are updated if they match on the `Name` field, otherwise new records are inserted.

3. Bulk DML Operations and Best Practices

Bulk DML operations in Apex allow developers to process large volumes of records efficiently. Instead of performing DML operations on individual records, bulk operations enable the manipulation of records in batches, reducing the number of round trips to the database and improving performance. Let’s discuss some best practices for bulk DML operations:

3.1 Use Collections for Bulk Data

List<Account> accountsToUpdate = [SELECT Id, Name FROM Account LIMIT 1000];
for(Account acc : accountsToUpdate) {
acc.Name += ‘ Updated’;
}
update accountsToUpdate;

Instead of performing DML operations on individual records in a loop, it’s recommended to use collections to process data in bulk. In the above example, we bulk update Account records by modifying their names and then performing a single `update` operation on the entire collection.

3.2 Bulkification of Triggers and Processes

When writing triggers or processes that perform DML operations, ensure they are bulkified to handle bulk data processing. Bulkification involves designing your code to operate efficiently on sets of records rather than individual records. This approach minimizes governor limit consumption and improves overall performance.

3.3 Efficient Querying

Optimize your SOQL queries to retrieve only the necessary data for DML operations. Use selective WHERE clauses and limit the number of fields queried to reduce query execution time and improve performance, especially when dealing with large datasets.

4. Error Handling and Considerations

When performing DML operations in Apex, it’s essential to handle potential errors gracefully. Common errors include DML exceptions due to validation rules, duplicate record errors, or governor limit exceptions. Utilize try-catch blocks to capture and handle exceptions appropriately, providing meaningful error messages to users and logging errors for troubleshooting purposes.

5. Conclusion

Database Manipulation Language (DML) operations are crucial for interacting with data in Salesforce, and Apex provides robust support for performing CRUD operations on records. By understanding transaction boundaries, governor limits, and best practices for bulk DML operations, developers can efficiently manipulate data while ensuring data integrity and system performance. By following the guidelines outlined in this article, developers can write efficient, scalable, and error-resilient code for DML operations in Apex.

This concludes our in-depth guide to DML operations in Apex. We’ve covered fundamental concepts, CRUD operations, bulk DML best practices, error handling, and considerations for building robust data manipulation solutions in Salesforce.

Resources for Further Learning

To further enhance your understanding of advanced Apex features and Salesforce development in general, here are some recommended resources:

- Salesforce Apex Developer Guide: The official Apex developer guide provides comprehensive documentation and examples for mastering Apex programming.
- Trailhead: Salesforce’s interactive learning platform offers a wide range of modules and trails on Apex development, asynchronous processing, integrations, and more.
- Salesforce Developer Blog: Stay updated with the latest news, tips, and best practices from Salesforce developers and experts through the official developer blog.
- Stack Exchange — Salesforce: Engage with the Salesforce community, ask questions, and share knowledge on Stack Exchange’s dedicated Salesforce platform.

--

--

Mohammad Usman

Trailblazer | Transforming Businesses through Salesforce Expertise | Salesforce Technical Architect, Consultant & Developer | Technical Lead