Skip to main content
Rohit . (360 Cloud Solution) 님이 #Apex에 질문했습니다

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

답변 4개
  1. 어제 오후 4:47

    Hi @Rohit .

     

    acc.Contacts is available because the query uses a Parent-to-Child Relationship Query:

    SELECT Id, Name,       (SELECT Id, Name, Department FROM Contacts)FROM Account

    The child Contacts are retrieved as part of the same SOQL query and stored in the acc.Contacts relationship collection. Therefore, no separate SOQL query is required inside the loop. 

     

    Regarding a large number of Contacts, the nested loop is valid, but retrieving every Contact just to count IT Contacts may be inefficient. If we only need the count, an Aggregate SOQL query

     with COUNT() and GROUP BY AccountId would be more efficient because the database performs the counting instead of Apex. 

     

    So, use the relationship query when you need to process Contact records; use Aggregate SOQL when you only need counts/statistics

    .  

     

    Hope this help !!.

0/9000