Managing Batch Execution Without DML Limits in Salesforce

Question
How to Create Accounts with Multiple Contacts in Salesforce Without Exceeding DML Limits?
I am trying to create accounts and associate 1,000 contacts with each account in Salesforce using a batch class. When managing batch execution without DML limits in Salesforce, I can successfully handle the required number of accounts (e.g., 10,000 or more) using batching. However, the process of creating associated contacts runs into the following error:
System.LimitException: Too many DML rows: 10001
Methods I attempted to resolve the issue include:
- Declaring the contacts at the class level and passing them to another batch class in the
finishmethod. However, this resulted in the error Batchable instance is too big. - Calling a queueable class from the
executemethod. This failed with the error Too many queueable jobs added to the queue.
Below is the code I used:
public class AccountBatchCreator implements Database.Batchable<String> {
private Integer numberOfAccountsToCreate;
public AccountBatchCreator(Integer numberOfAccountsToCreate) {
this.numberOfAccountsToCreate = numberOfAccountsToCreate;
}
public Iterable<String> start(Database.BatchableContext context) {
List<String> accountNames = new List<String>();
for (Integer i = 0; i < numberOfAccountsToCreate; i++) {
accountNames.add('Test Account --+' + i);
}
return accountNames;
}
public void execute(Database.BatchableContext context, List<String> scope) {
List<Account> accounts = new List<Account>();
for (String accountName : scope) {
accounts.add(new Account(Name = accountName));
}
insert accounts;
List<Contact> contacts = new List<Contact>();
for (Account account : accounts) {
for (Integer i = 0; i < 1000; i++) {
contacts.add(new Contact(
AccountId = account.Id,
AssistantName = 'test contact',
LastName = 'te',
FirstName = 'st'
));
}
}
insert contacts;
}
public void finish(Database.BatchableContext context) {
System.debug('Batch processing completed.');
}
}Is there an effective way to resolve this issue and create accounts along with their associated contacts while staying within Salesforce’s governor limits?
Answer
The issue revolves around creating accounts and associating 1,000 contacts with each account in Salesforce. If the number of accounts is large, say 10,000, the batch process runs into the System.LimitException: Too many DML rows: 10001 error because Salesforce enforces a governor limit of 10,000 DML rows per transaction. Attempts to resolve this by calling another batch or queueable job from the execute method also fail, as Salesforce imposes limits on chained batch and queueable jobs. So, how can this problem be solved effectively?
Start your Salesforce career with our Salesforce training in Singapore, offering job-ready skills and hands-on experience through real-world projects. Join our free demo session today!
One solution is to use a batch-chaining mechanism by splitting the creation of accounts and their associated contacts into separate batch jobs. Another option is to use a combination of a batch job and queueable jobs, limiting the DML operations in each job to stay within governor limits.
Here’s how you can address the issue using a two-step batch approach:
Code Example:
Batch 1: Create Accounts This batch job will focus solely on creating the accounts.
public class AccountBatchCreator implements Database.Batchable<Integer> {
private Integer numberOfAccountsToCreate;
public AccountBatchCreator(Integer numberOfAccountsToCreate) {
this.numberOfAccountsToCreate = numberOfAccountsToCreate;
}
public Iterable<Integer> start(Database.BatchableContext context) {
List<Integer> accountChunks = new List<Integer>();
for (Integer i = 0; i < numberOfAccountsToCreate; i += 200) {
accountChunks.add(i);
}
return accountChunks;
}
public void execute(Database.BatchableContext context, List<Integer> scope) {
List<Account> accounts = new List<Account>();
for (Integer i : scope) {
accounts.add(new Account(Name = 'Test Account -- ' + i));
}
insert accounts;
}
public void finish(Database.BatchableContext context) {
// Start the contact creation batch job
Database.executeBatch(new ContactBatchCreator(), 200);
}
}Batch 2: Create Contacts This batch job will take the accounts and create the contacts in chunks.
public class ContactBatchCreator implements Database.Batchable<SObject> {
public Iterable<SObject> start(Database.BatchableContext context) {
return [SELECT Id FROM Account];
}
public void execute(Database.BatchableContext context, List<SObject> scope) {
List<Contact> contacts = new List<Contact>();
for (SObject sObj : scope) {
Account account = (Account)sObj;
for (Integer i = 0; i < 1000; i++) {
contacts.add(new Contact(
AccountId = account.Id,
AssistantName = 'Test Contact',
LastName = 'LastName',
FirstName = 'FirstName'
));
if (contacts.size() == 100) { // Insert in small batches to avoid limits
insert contacts;
contacts.clear();
}
}
}
if (!contacts.isEmpty()) {
insert contacts;
}
}
public void finish(Database.BatchableContext context) {
System.debug('All contacts created successfully.');
}
}Explanation:
- The
AccountBatchCreatorbatch job creates accounts in chunks and inserts them. - Upon completion, it triggers the
ContactBatchCreatorbatch job in thefinishmethod. - The
ContactBatchCreatorcreates contacts in smaller batches (100 at a time) to avoid DML limits.
This method prevents hitting the DML row limit by breaking the task into manageable parts. Another variation could involve using a queueable job for contact creation, but it must account for the limit on queueable job chaining.
See also: Top 20 Salesforce Architect Interview Questions
Salesforce Training with Real-World Project Experience in Singapore
Our Salesforce training program offers personalized mentorship, thorough certification exam preparation, and expert interview coaching to help you excel in today’s competitive job market. With hands-on project experience, detailed study materials, and ongoing guidance, you’ll gain the confidence and expertise to succeed. By the end of the program, you’ll be ready to earn certifications and showcase practical skills that employers value. Start your Salesforce journey with us and unlock exciting career opportunities!
Our Salesforce training in Singapore delivers an immersive learning experience tailored to equip you with the expertise to thrive in the CRM industry. Covering key areas like Salesforce Admin, Developer, and AI, the program combines theoretical knowledge with practical, real-world applications. Through industry-relevant projects and assignments, you’ll develop the skills to solve complex business challenges using Salesforce solutions. Led by seasoned instructors, the training strengthens your technical abilities and deepens your CRM knowledge.
Take the first step toward a successful Salesforce career. Join us for a FREE Demo session today!

