We need to find Accounts that have Contacts whose Department is "IT", and print the Account Name along with the number of IT Contacts.
I tried this:
for (Account acc : [
SELECT Id, Name, (SELECT Id, Name, Department FROM Contacts)
FROM Account
]) {
Integer count = 0;
for (Contact con : acc.Contacts) {
if (con.Department == 'IT') {
count++;
}
}
System.debug(acc.Name + ' → IT Contacts: ' + count);
}
My question:
Why is acc.Contacts available inside the outer loop even though we didn't execute a separate SOQL query for Contacts?
Also, what happens if an Account has a very large number of Contacts? Is there a better/bulk-safe approach than using the nested loop
?
#Apex #Salesforce Developer
Hi,
Here is the most optimized version. Give a try
AggregateResult[] groupedResults
= [SELECT Account.Name AccountName, Count(Id) ContactCount
FROM Contact WHERE Department IN ('IT')
GROUP BY Account.Name];
for (AggregateResult ar : groupedResults) {
System.debug(ar.get('AccountName') + ' → IT Contacts: ' + ar.get('ContactCount'));
}