Skip to content

Instantly share code, notes, and snippets.

@salesforceBen
Created February 9, 2020 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save salesforceBen/88e09368e5fc4fb45adba4379c817ffa to your computer and use it in GitHub Desktop.
Save salesforceBen/88e09368e5fc4fb45adba4379c817ffa to your computer and use it in GitHub Desktop.
// SOQL in a for loop issue:
List<Account> accounts = [SELECT Id, Name FROM Account];
List<Integer> contactCount = new List<Integer>();
for (Integer i = 0; i <= accounts.size(); i++)
{
Integer count = [SELECT COUNT() FROM Contact WHERE AccountId IN : accounts ];
contactCount.add(count);
}
// SOQL in a for loop fix:
Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Id FROM Account]);
Map<String, Integer> accountNamesAndRespectiveContactCounts = new Map<String, Integer>();
for(Account accountObject : [SELECT Name, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :accountMap.keySet()])
{
accountNamesAndRespectiveContactCounts.put(accountObject.Name, accountObject.Contacts.size());
}
system.debug('accountObject map is: ' + accountNamesAndRespectiveContactCounts);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment