Salesforce Certified Platform Developer free question 1 / 10 · Domain 1: Developer Fundamentals
In the following Apex, you want to declare a variable that receives the related contacts for each account. Which declaration for X matches the Apex Developer Guide? for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts) FROM Account WHERE Name = 'Acme']) { X }
- Contact cons = a.getContacts();
- Contact cons = a.Contacts;
- Contact[] cons = a.Contact__r;
- Contact[] cons = a.Contacts;
Show the answer and explanation
Answer: D
Why this is correct
"Understanding Foreign Key and Parent-Child Relationship SOQL Queries" in the Apex Developer Guide shows how Apex receives the result of a subquery over a parent-child relationship. In its example, each account runs a subquery for its contacts, and the loop receives the result as Contact[] cons = a.Contacts;. The subquery result lands in the field named by the relationship name, Contacts, as a list of contacts, so it is received as an array (list) type.
Why the other options are wrong
"Contact cons = a.Contacts;" … A single Contact receives the subquery result in the guide's example only when the subquery has LIMIT 1 and returns one contact. The subquery in this question does not limit the rows, so the result is received as a list.
"Contact[] cons = a.Contact__r;" … For a parent-child relationship between standard objects, such as account to contact, the relationship name is the plural of the child object (Contacts) ("Using Relationship Queries" in the SOQL and SOSL Reference). The suffix __r is added to the names of custom relationships. It is not part of a standard relationship name.
"Contact cons = a.getContacts();" … This makes two mistakes at once. The guide's example reads the subquery result through the relationship name, a.Contacts, and does not call a method that starts with get. A subquery that does not limit its rows is also received as a list, not as a single Contact.
Key point
The result of a parent-to-child subquery is stored in the parent sObject's relationship-name field and is received from there as a list. The same page also shows that a single sObject can receive it, but only when the subquery is limited to one row with LIMIT 1.