Build Contacts with one query and one insert
A query inside a loop costs one SOQL query per record, and a transaction allows only 100.
Your task
Rewrite the slow loop so it finds every parent Account with one query and a Map, then inserts all Contacts at once.
String tag = 'AS-SHIP-' + UserInfo.getUserId() + '-' +
String.valueOf(Datetime.now().getTime());
List<Account> parents = new List<Account>{
new Account(Name = tag + '-North'),
new Account(Name = tag + '-South')
};
insert parents;
List<String> parentNames = new List<String>{
tag + '-North', tag + '-South', tag + '-North', tag + '-South', tag + '-North'
};
Integer queriesBefore = Limits.getQueries();
Integer dmlBefore = Limits.getDmlStatements();
for (String parentName : parentNames) {
Account parent = [SELECT Id FROM Account WHERE Name = :parentName LIMIT 1];
insert new Contact(LastName = tag + '-Contact', AccountId = parent.Id);
}
System.debug('Queries used: ' + (Limits.getQueries() - queriesBefore));
System.debug('DML used: ' + (Limits.getDmlStatements() - dmlBefore));Requirements
- Looks parents up in a Map should be present
- Queries parents with IN should be present
- Uses one query should be printed as
Queries used: 1 - Uses one DML statement should be printed as
DML used: 1 - Links every Contact should be printed as
Contacts linked: 5