
DML statements in Salesforce apex

Table of Contents
- What is DML in Salesforce?
- Insert Operation
- Update Operation
- Delete Operation
- Undelete Operation
- Upsert Operation
- FAQs
- How many DML are in Salesforce?
- Difference between DML and SOQL
- What are DML queries?
- How to avoid SOQL in for loop?
- What is the maximum limit of SOQL?
- How to avoid 101 error in Salesforce?
- What is the timeout for SOQL?
- How do I handle governor limits?
Apex is a data-driven language registered on the Lightning Platform. Therefore, it has direct access to your data in Salesforce. Unlike other programming languages ​​that require additional configuration to connect to data sources.
What is DML in Salesforce?
DML stands for Data Manipulation Language which lets you Insert, Update, Delete, Undelete records in Apex. DML allows you to perform operations on a single sObject record or in bulk on a list of sObjects records at once. It is efficient to use sObjects lists for processing records. DML is the key part of Apex since almost every business case requires updating databases.
Let’s take a look at some examples of DML operations like Insert, Update, Delete, etc.
Insert Operation:
The insert operation inserts new records into the database. Using the Insert DML statement, you can create records of any Standard or Custom object.
For example: In this example, we are inserting an account record and two contact records related to that account.
// Create the account sObject
Account accObject = new Account();
accObject.Name = ‘Test Account’;
accObject.Website =’www.salesforce.com’;
// Insert the account by using DML
Insert accObject ;
// Create the contact sObject List
List<Contact> contactList = new List<Contact>();
// Create the contact sObject
Contact con1 = new Contact();
con1.FirstName =’first’;
con1.LastName =’contact’;
con1.AccountId =’accObject.Id’;
// Adding the sObject to the list
contactList.add(con1);
// Create the contact sObject
Contact con2 = new Contact();
con2.FirstName =’second’;
con2.LastName =’contact’;
con2.AccountId =’accObject.Id’;
// Adding the sObject to the list
contactList.add(con2);
// Insert the contact list by using DML
Insert contactList;
Prepare for your next job with confidence by exploring the Ultimate Salesforce interview questions and answers. Gain insights into what to expect and how to impress your interviewer.
Update Operation:
Update operations are used to update existing records stored in the database. You have to query the existing records from the database to perform an update operation on them.
Checkout: Variables in Salesforce Apex
Example: In this example, we are querying the account which we have inserted in the above insert operation example and will update the name field on it.
Account accountRecord =[Select Id, Name from Account where Name = ‘Test Account’ LIMIT 1];
accountRecord.Name = ‘Updated Name’;
// updating the account record using DML
update accountRecord;
// To verify the account name whether it is updated or not
Account accountRecord =[Select Id, Name from Account where Name = ‘Updated Name’ LIMIT 1];
// Display the account record in the debug logs
system.debug(‘account afterUpdate::::’+accountRecord);
Checkout: Data types in Salesforce Apex
Delete Operation:
Delete operations are performed on the existing records in the database. Deleted records are not deleted permanently from salesforce; they are stored for 15 days in the recycle bin; from there they can be restored within 15 days.
Example: In this example, we delete the account record which we updated in the above update operation example.
// Querying the account record
Account accn =[Select Id, Name from Account where Name = ‘Updated Name’ LIMIT 1];
// Deleting the account record using DML
Delete accn;
// To verify whether account record is deleted or not
Account accn =[Select Id, Name from Account where Name = ‘Updated Name’ LIMIT 1];
if(accn.size() ==0){
// Display the message in the debug logs
system.debug(‘account does not exist’);
}else{
// Display the message in the debug logs
system.debug(‘account existed’);
}
Read more: Salesforce apex programming examples
Undelete Operation:
When you delete the records, they are stored in the recycle bin for 15 days and after 15 days they are deleted permanently from the salesforce. To query the deleted records from the recycle bin, we have to use the ALL ROWS parameter in the Soql query.
Example: In this example, we are retrieving account records that we have deleted in the above delete operation example.
// Querying the account record
Account accn = [select Id, Name from Account where Name =’Updated Name’ ALL ROWS];
// Undeleting the account record using DML
Undelete accn ;
// To verify whether account record is restored or not
Account accn = [select Id, Name from Account where Name =’Updated Name’];
// Display the account record in the debug logs
system.debug(‘restored account record:::’+accn);
Read more: Array methods in Salesforce Apex
Upsert Operation:
Upsert statements allow you to insert new records or update existing records in a single call. Upsert statements determine whether a record already exists or not by using the record’s ID.
Example: In this example, we are updating the account name of an existing account record from ‘Updated Name’ to ‘salesforce Account’ and also creating a new account record.
// Querying the account records
Account[] acctsList = [SELECT Id, Name, BillingCity
FROM Account WHERE Name=’Updated Name’];
//Iterating over the account records
for (Account a : acctsList) {
a.Name =’Salesforce account’;
}
// Creating a new record
Account newAcct = new Account(Name =’SF Account’);
// Adding the new record to the list
acctsList.add(newAcct);
// Upserting the account List using DML
Upsert acctsList;
Read more: Loops in Salesforce Apex
Frequently Asked Questions (FAQS)
1. What are DML operations in Salesforce?
DML operations in Salesforce are Data Manipulation Language operations that allow me to interact with the database. These operations let me insert, update, delete, or restore records in Salesforce. For instance, if I need to add a new contact to the database, I use the insert
DML operation. If I need to update an existing account’s details, I use the update
DML operation. DML operations are essential because they enable me to manipulate data programmatically within my Salesforce environment. These operations ensure that my data is accurate and up-to-date, which is critical for maintaining good customer relationships and making informed business decisions.
Checkout: Data types in Salesforce Apex
2. What are the four commands in DML?
In Salesforce, there are four main commands in DML: Insert, Update, Delete, and Undelete. Each command has a specific purpose:
- Insert: Adds new records to the database. For example, when I onboard a new customer, I use the
insert
command to add their information to Salesforce. - Update: Modifies existing records. For instance, if a customer updates their address, I use the
update
command to reflect this change in their record. - Delete: Removes records from the database. If a customer leaves, I can use the
delete
command to remove their record. - Undelete: Restores records that were previously deleted. If a customer returns, I use the
undelete
command to restore their old record.
3. How many DML are in Salesforce?
Salesforce provides four primary DML operations: Insert, Update, Delete, and Undelete. These operations cover the fundamental actions I need to manipulate data within the Salesforce platform. Each operation allows me to perform specific tasks on the records in my database, ensuring that I can effectively manage and maintain the integrity of my data. By using these operations, I can keep my Salesforce data accurate and relevant, which is vital for day-to-day business operations and long-term strategic planning.
Read more: Salesforce apex programming examples
4. What is the DML limit 10000 in Salesforce?
In Salesforce, there is a governor limit that restricts me to a maximum of 10,000 DML operations per transaction. This limit ensures that I do not overuse system resources and helps maintain performance and stability. For example, if I’m running a batch process to update a large number of records, I need to be mindful of this limit to avoid hitting the governor limit, which would cause the transaction to fail. To manage large volumes of data, I can use batch processing to handle the data in smaller chunks, ensuring each batch stays within the DML limits. This approach helps me efficiently process large datasets without encountering errors.
Read more: Approval Process in Salesforce.
5. What is the difference between DML and SOQL in Salesforce?
In Salesforce, DML (Data Manipulation Language) and SOQL (Salesforce Object Query Language) serve different purposes. DML is used to manipulate data, meaning it allows me to insert, update, delete, or undelete records in the database. For example, if I need to add a new contact, I use DML operations like insert
or update
. On the other hand, SOQL is used to query data from the database. It helps me retrieve records based on specific criteria. For instance, if I want to find all contacts living in New York, I use a SOQL query. In essence, DML modifies data, while SOQL retrieves data.
Aspect | DML (Data Manipulation Language) | SOQL (Salesforce Object Query Language) |
---|---|---|
Purpose | Modify data | Retrieve data |
Operations | Insert, Update, Delete, Undelete | Select queries |
Usage | Adding or changing records | Fetching records based on criteria |
Example | Insert new contact | Find contacts in New York |
Read more: Understanding roles and profiles in salesforce.
6. Can we use DML in trigger Salesforce?
Yes, I can use DML operations in a Salesforce trigger. A trigger allows me to perform custom actions before or after events, like insertions, updates, or deletions of records. For example, if I want to automatically create a task every time a new account is created, I can write a trigger that uses the insert
DML operation to add the task. However, I need to be cautious about governor limits and avoid using too many DML operations within a single trigger to prevent hitting the limits and causing errors.
7. What are the two types of DML?
In Salesforce, there are two types of DML: synchronous and asynchronous.
a. Synchronous DML
Synchronous DML operations are executed immediately and are typically used in triggers and Visualforce controllers. For example, when I update a record from a Visualforce page, the update happens right away.
b. Asynchronous DML
Asynchronous DML operations, such as those in batch Apex or future methods, are queued and executed when system resources are available. This type of DML is useful when I need to process large volumes of data without running into governor limits, as the operations are spread out over time.
Read more: Types of relationships in Salesforce
8. What are DML queries?
DML queries refer to the operations that involve data manipulation in Salesforce, such as Insert, Update, Delete, and Undelete. Although the term “DML queries” is sometimes used, it’s important to note that actual queries are performed using SOQL (Salesforce Object Query Language). DML operations directly alter the database records. For example, if I want to add a new contact, I use the insert
operation. If I want to change an existing contact’s details, I use the update
operation. These operations are essential for maintaining and updating the records in my Salesforce environment.
DML Operation | Description | Example |
---|---|---|
Insert | Adds new records to the database | Insert new contact |
Update | Modifies existing records | Change contact details |
Delete | Removes records from the database | Remove a departing customer |
Undelete | Restores records that were previously deleted | Restore a returning customer |
9. What is the most common DML command?
The most common DML command in Salesforce is the Insert operation. This command is used to add new records to the database.
For example, every time I need to add a new contact or account, I use the insert
DML operation. It’s essential for creating new records as part of day-to-day business processes, such as onboarding new customers, adding new leads, or creating new cases. The insert
command is fundamental in ensuring that new data is accurately captured and stored in Salesforce, enabling me to maintain up-to-date records.
10. How to avoid SOQL in for loop in Salesforce?
To avoid SOQL in a for loop in Salesforce, I need to follow best practices to prevent hitting governor limits. Instead of querying inside the loop, I should query outside the loop and store the results in a collection, like a list or a map.
For example, if I need to retrieve accounts and their related contacts, I first run a SOQL query to get all the necessary accounts, then loop through the results. This way, I avoid making multiple SOQL calls within the loop, which helps maintain performance and prevents exceeding the limit of 100 SOQL queries per transaction.
Read more: Array methods in Salesforce Apex
To avoid SOQL in a for loop in Salesforce, you should query the data outside the loop and store it in a collection. Here’s an example demonstrating how to do this:
Incorrect Way: SOQL inside a loop
for (Account acc : [SELECT Id, Name FROM Account WHERE Industry = 'Technology']) {
List<Contact> contacts = [SELECT Id, Name FROM Contact WHERE AccountId = :acc.Id];
// Process contacts
}
Correct Way: SOQL outside the loop
// Query accounts
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Industry = 'Technology'];
// Collect Account IDs
Set<Id> accountIds = new Set<Id>();
for (Account acc : accounts) {
accountIds.add(acc.Id);
}
// Query contacts once, outside the loop
List<Contact> contacts = [SELECT Id, Name, AccountId FROM Contact WHERE AccountId IN :accountIds];
// Process contacts
Map<Id, List<Contact>> accountContactsMap = new Map<Id, List<Contact>>();
for (Contact contact : contacts) {
if (!accountContactsMap.containsKey(contact.AccountId)) {
accountContactsMap.put(contact.AccountId, new List<Contact>());
}
accountContactsMap.get(contact.AccountId).add(contact);
}
// Now you can process the contacts for each account
for (Account acc : accounts) {
List<Contact> relatedContacts = accountContactsMap.get(acc.Id);
// Process relatedContacts
}
In this example, the SOQL queries are performed outside the loop, reducing the number of SOQL queries and adhering to best practices to avoid governor limits.
11. How to avoid DML inside for loop?
To avoid DML inside a for loop in Salesforce, I should batch my DML operations. Instead of performing a DML operation for each record within the loop, I can collect all the records in a list and perform a single DML operation outside the loop. For example, if I need to update multiple contacts, I add each contact to a list during the loop. After the loop completes, I perform a single update
operation on the list. This approach reduces the number of DML operations, preventing governor limit exceptions and improving performance.
To avoid DML inside a for loop in Salesforce, you should collect the records that need to be processed in a list and perform the DML operation outside the loop. Here’s an example demonstrating how to do this:
Incorrect Way: DML inside a loop
for (Account acc : [SELECT Id, Name FROM Account WHERE Industry = 'Technology']) {
acc.Name = acc.Name + ' - Updated';
update acc; // This DML operation is inside the loop
}
Correct Way: DML outside the loop
// Query accounts
List<Account> accountsToUpdate = [SELECT Id, Name FROM Account WHERE Industry = 'Technology'];
// Collect the records to be updated
for (Account acc : accountsToUpdate) {
acc.Name = acc.Name + ' - Updated';
}
// Perform the DML operation outside the loop
update accountsToUpdate;
In this example, the update
DML operation is performed outside the loop, which reduces the number of DML operations and ensures that the code adheres to Salesforce governor limits.
12. How to query more than 50,000 records in Salesforce?
To query more than 50,000 records in Salesforce, I can use Batch Apex or Apex QueryLocator. Batch Apex allows me to process records in chunks, with each chunk containing a maximum of 50,000 records. This way, I can process large data sets efficiently without hitting governor limits. For instance, if I need to process 100,000 records, Batch Apex will handle them in two chunks. Another approach is using the Database.queryLocator
in a batch class, which helps me retrieve large sets of records by splitting them into manageable batches, ensuring smooth processing and compliance with limits.
13. What is the maximum limit of SOQL in Salesforce?
In Salesforce, the maximum limit of SOQL queries is 100 SOQL queries per transaction. This governor limit ensures that the system resources are not overused and helps maintain performance and stability. For example, if I’m writing a trigger or an Apex class, I need to be mindful of the number of SOQL queries I execute. To stay within this limit, I can optimize my code by combining multiple queries into one or using collections like lists and maps to store results from a single query. This way, I can efficiently retrieve data without exceeding the SOQL query limit.
Read more: Loops in Salesforce Apex
14. How many records can be returned by SOQL?
A single SOQL query can return a maximum of 50,000 records in Salesforce. If I need to retrieve more than 50,000 records, I should use Batch Apex or the QueryLocator method. For instance, when I need to process a large data set, such as retrieving all accounts for a massive report, using Batch Apex allows me to handle records in smaller, manageable chunks. Each chunk can process up to 50,000 records, ensuring that I stay within the limits while still being able to work with large volumes of data effectively.
15. How do I delete 10000 records in Salesforce?
To delete 10,000 records in Salesforce, I can use Batch Apex. Batch Apex processes records in chunks, making it ideal for handling large data sets without hitting governor limits. For example, if I need to delete 10,000 outdated contact records, I can write a batch class that processes these records in batches of up to 200. This approach ensures that the deletion process is efficient and stays within the limits. Additionally, I can use the Data Loader
tool for bulk deletions, which allows me to delete large numbers of records by uploading a CSV file containing the IDs of the records to be deleted.
16. How to avoid 101 error in Salesforce?
The 101 error in Salesforce, also known as the “Too many SOQL queries” error, occurs when more than 100 SOQL queries are executed in a single transaction. To avoid this, I need to optimize my code. One effective strategy is to move SOQL queries outside of loops and use collections like lists and maps to handle data efficiently. For example, instead of querying inside a loop to get contact details for each account, I can perform a single query to get all necessary contacts at once, then process the results. This approach reduces the number of queries and helps prevent the 101 error.
Here is the solution for too many SOQL queries error.
17. How do I bypass a trigger in Salesforce?
To bypass a trigger in Salesforce, I typically use a custom setting or a custom metadata type to control whether the trigger should execute. For example, I can create a custom setting called Trigger_Control
with a boolean field isActive
. In the trigger, I check the value of this field before executing the logic. If isActive
is true
, the trigger runs; if false
, it doesn’t. This approach is handy during data migrations or bulk operations when I need to disable triggers temporarily to avoid unnecessary processing or hitting governor limits.
Custom Setting Example:
// Custom setting definition
public class TriggerControl {
public static Boolean isActive() {
Trigger_Control__c control = Trigger_Control__c.getOrgDefaults();
return control != null && control.isActive__c;
}
}
// Trigger example
trigger AccountTrigger on Account (before insert, before update) {
if (TriggerControl.isActive()) {
// Your trigger logic here
for (Account acc : Trigger.new) {
// Process account
}
}
}
In this example, the trigger logic only executes if the isActive
field in the Trigger_Control
custom setting is set to true
. To bypass the trigger, simply set isActive
to false
.
18. What is the timeout for SOQL?
In Salesforce, the timeout for SOQL queries is generally 120 seconds. This means that a SOQL query should complete within this time frame. If it takes longer, Salesforce will terminate the query, and I’ll receive an error. To avoid this, I should optimize my queries to ensure they run efficiently. For example, using selective filters and indexing fields can help speed up query performance. Additionally, breaking down complex queries into simpler ones or using Batch Apex for large data sets can help ensure that my queries complete within the allowable time limit.
Read more: Loops in Salesforce Apex
19. How do I handle null values in SOQL?
Handling null values in SOQL is straightforward. I can use the NULL
keyword in my query to check for null values. For example, if I want to find all contacts without an email address, I write a query like this: SELECT Id, Name FROM Contact WHERE Email = NULL
. Similarly, I can check for non-null values using != NULL
. When writing Apex code, it’s also a good practice to use null checks to avoid null pointer exceptions. For instance, before processing a field, I check if it’s null: if (contact.Email != null) { // process email }
.
Read more: SOQL in Salesforce
To handle null values in SOQL, you can use the NULL
keyword. Here’s a straightforward example:
If you want to find all contacts without an email address:
SELECT Id, Name FROM Contact WHERE Email = NULL
To find contacts with a non-null email address:
SELECT Id, Name FROM Contact WHERE Email != NULL
In Apex, ensure you check for null values before processing fields to avoid null pointer exceptions:
List<Contact> contacts = [SELECT Id, Name, Email FROM Contact WHERE Email = NULL];
for (Contact contact : contacts) {
if (contact.Email != null) {
// Process email
}
}
This ensures that you handle records appropriately, whether the field values are null or not.
20. How do I handle governor limits in Salesforce?
Handling governor limits in Salesforce requires careful planning and optimization of my code. Some strategies include:
- Bulkification: Processing records in bulk rather than one at a time. For example, using collections like lists or maps to handle data and performing DML operations outside loops.
- Efficient Queries: Using selective SOQL queries and minimizing the number of queries executed. Combining multiple queries into one when possible.
- Using Asynchronous Processes: Leveraging Batch Apex, future methods, and queues to process large data sets asynchronously, spreading the workload over time.
- Optimizing Logic: Breaking down complex logic into smaller, reusable methods and ensuring that only necessary code executes during a transaction.
Next chapter is database methods and previous chapter is interfaces in Salesforce apex.