Skip to content

Instantly share code, notes, and snippets.

@salesforceBen
Last active March 30, 2023 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save salesforceBen/8c8531236ff13ce3d5da62a688586e08 to your computer and use it in GitHub Desktop.
Save salesforceBen/8c8531236ff13ce3d5da62a688586e08 to your computer and use it in GitHub Desktop.
// Too many DML's issue:
List<Account> accountList = new List<Account>();
Account accountObject;
for (Integer i = 0; i < 150; i++)
{
accountObject = new Account();
accountObject.Name = 'Test ' + i;
accountList.add(accountObject);
}
insert accountList;
Contact contactObject;
for (Account accountIterator : [SELECT Id, Name FROM Account])
{
contactObject = new Contact();
contactObject.AccountId = accountIterator.Id;
contactObject.LastName = 'Surname ' + accountIterator.Name;
insert contactObject;
}
// Too many DML's fix:
List<Contact> contactList = new List<Contact>();
Contact contactObject;
for (Account accountIterator : [SELECT Id, Name FROM Account LIMIT 150])
{
contactObject = new Contact();
contactObject.AccountId = accountIterator.Id;
contactObject.LastName = 'Surname ' + accountIterator.Name;
contactList.add(contactObject);
}
if (contactList.size() > 0)
{
insert contactList;
}
system.debug('Size of contact list is: ' + contactList.size());
system.debug('Count of DML statements: ' + Integer.valueOf(Limits.getDmlStatements()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment