Given a list of Opportunity records named opportunityList, which code snippet is best for querying all Contacts of the Opportunity's Account?
A.
Java
List
Set
for(Opportunity o : opportunityList){
accountIds.add(o.AccountId);
}
for(Account a : [SELECT Id, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :accountIds]){
contactList.addAll(a.Contacts);
}
B.
20
Java
List
for ( Contact c : [SELECT Id FROM Contact WHERE AccountId IN :opportunityList.AccountId ]){
contactList.add(c);
}
22
In Apex, 'bulkification' is the practice of ensuring code can handle multiple records efficiently without hitting governor limits. Snippet A demonstrates the correct bulkified approach for this requirement. It first iterates through the opportunityList to collect all unique AccountId values into a Set. Then, it performs a single SOQL query to retrieve all relevant Accounts and their child Contacts using a subquery (Inner Join). This ensures that the code only consumes one SOQL query regardless of how many opportunities are in the input list.
Snippet B is syntactically incorrect and will fail to compile. In Apex, you cannot use dot-notation (like opportunityList.AccountId) on a List collection to retrieve a set of IDs from its elements. To access the AccountId of records within a list, you must iterate through the list or use a map. Even if corrected to use a proper ID collection, Snippet A is often preferred when you need the relationship context between the Account and its Contacts. Most importantly, Snippet A correctly identifies the need to extract IDs into a separate collection before querying, which is a fundamental requirement for writing scalable Apex. It avoids the 'Query in a loop' anti-pattern and adheres to the platform's execution model.
==========
Currently there are no comments in this discussion, be the first to comment!