Inserting Multiple SObject Records in a Single DML Statement
In Salesforce development, optimizing DML operations is one of the most crucial aspects of writing scalable and efficient Apex code. You may already know that salesforce governs Governor Limits to ensure that shared resources are used efficiently. One common question developers face is:
Can we insert records of different sObjects such as Accounts, contacts, opportunities etc. in a single DML statement ?
The Answer is Yes! You can insert records of different sObjects in a single DML statement using a List<sObject>
How to insert multiple sObject records in a single DML?
As we know sObject is a parent of all standard and custom sObjects. We can use sObject to store standard or custom sObjects. So, the idea is to create a different sObject records and add it to List<sObject> and perform DML operation on the List<sObject>
Insert unrelated multiple sObject records in a single DML
In the below example we have initialized sObject records for Account and Contact and add them to List<sObject> inserted them together using a Database method.
Account acc = new Account( Name = 'John Doe',
Industry = 'Agriculture');
Contact con = new Contact( FirstName = 'John',
LastName = 'Doe');
Database.SaveResult[] results = Database.insert( new List<sObject> {acc,con}, false );
for(Database.SaveResult res : results){
if(res.isSuccess()){
System.debug('Record created successfully '+res.getId());
}else{
System.debug('Error '+System.JSON.serialize(res.getErrors()));
}
}
Output
USER_DEBUG [9]|DEBUG|Record created successfully 001NS000027L0b3YAC USER_DEBUG [9]|DEBUG|Record created successfully 003NS00001Trtd3YAB LIMIT_USAGE_FOR_NS Number of DML statements: 1 out of 150 LIMIT_USAGE_FOR_NS Number of DML rows: 2 out of 10000
In a normal scenario, when we use multiple insert statements, each insert statement counts as one DML statement. But with this approach we can combine records from different sObject records into single List<sObject> and insert them all at once.
Insert related multiple sObject records in a single DML
Normally, we create parent record first then, we create a child record with parent records’ Id. But this way of inserting related record can increase number of DML statements in a transaction.
Account acc = new Account( Name = 'John Doe',
Industry = 'Agriculture');
insert acc;
Contact con = new Contact( FirstName = 'John',
LastName = 'Doe',
AccountId = acc.Id);
insert con;
You can use external Id to create a parent child record of different sObject type in a single step. Follow below steps to achieve it.
- Declare and initialize a child sObject record.
- Declare and initialize parent sObject record with only external Id field.
- Set the lookup field on child sObject record to parent sObject reference record we just created.
- Create a new parent record with all the required fields and external Id. This sObject record we will pass in DML statement.
- Call
insertstatement by passingList<sObject>Please make sure parent record must be at lower index than child record.
Contact con = new Contact( FirstName = 'John',
LastName = 'Doe');
Account refAcc = new Account( Customer_Id__c = 'EXT_Id_001' );
con.Account = refAcc;
Account accToInsert = new Account( Customer_Id__c = 'EXT_Id_001',
Name = 'John Doe',
Industry = 'Agriculture');
Database.SaveResult[] results = Database.insert( new List<sObject> {accToInsert,con}, false );
for(Database.SaveResult res : results){
if(res.isSuccess()){
System.debug('Record created successfully '+res.getId());
}else{
System.debug('Error '+System.JSON.serialize(res.getErrors()));
}
}
Output
USER_DEBUG [14]|DEBUG|Record created successfully 001NS000027L5qwYAC USER_DEBUG [14]|DEBUG|Record created successfully 003NS00001Ts4yIYAR LIMIT_USAGE_FOR_NS Number of DML statements: 1 out of 150 LIMIT_USAGE_FOR_NS Number of DML rows: 2 out of 10000
Above example shows how to create a contact record with its parent account record in a same DML statement. First, we create a contact record and populate some of its fields. then, we created two account records with same external Id. One account record is only for setting external Id and second is for account creation. Then we pass List<sObject> to Database.insert method. SObject list contains parent account and child contact record.
Benefits of using Single DML statement
- Reduce DML count which is 150 per transaction
- Improved Performance, combining operations minimizes database trips
- Dynamic Use Cases, works well when object types are not known at compile time
Inserting multiple Salesforce object records in a single DML statement is a powerful yet situational feature in Apex. It can help optimize performance and reduce DML operations, but it also requires careful error handling and transaction design. If used wisely especially, in batch processes or frameworks it can make your code cleaner, faster and more efficient.