Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
// 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 ];
// 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