I understand it is possible to perform queries on related entities such as

SELECT (SELECT Name FROM Contacts) FROM Account

However, it is not obvious to me what's the result type of such a query if I try to assign it to a sObject / collection sObject.

Is that a List<Account> ? Is that a List<Contact> ?

  • List of accounts with a field Contacts pointing to a list of Contacts
    – benahm
    Mar 17, 2017 at 13:29

2 Answers 2


The result of any query will always be of a type that corresponds to the top level FROM clause.

List<Account> records = [SELECT ... FROM Account];

It doesn't matter what's in the SELECT clause, nor any other clauses in your query. Sometimes, you might assign it to a single record rather than a list, but the SObjectType would remain the same:

Account record = [SELECT ... FROM Account LIMIT 1];

You can pull child records as if the related list were a field:

for (Account record : records)
    List<Contact> children = record.Contacts;
  • Thanks, it looks like the account.Contacts list is empty although I have created an account and attached two contacts
    – Edmondo
    Mar 17, 2017 at 13:13
  • @Edmondo Did you attach them through the AccountId field or some other lookup?
    – Adrian Larson
    Mar 17, 2017 at 13:14
  • 1
    Contact contact = new Contact(FirstName = 'Mark', LastName = 'Smith', Account = testAccount); doesn't work, why does one need to attach on the AccountId?
    – Edmondo
    Mar 17, 2017 at 13:15
  • Using the accountID works, though it's not obvious for me why
    – Edmondo
    Mar 17, 2017 at 13:16
  • 1
    @Edmondo The Account field is name pointing and using it to update the relationship has special rules. See also: Set Relationship Via Name Pointing Field?
    – Adrian Larson
    Mar 17, 2017 at 13:18

In that example, you probably will get a list of accounts.

List<Account> acc =[SELECT Id,Name, (SELECT FirstName, LastName FROM Contacts) FROM Account]; 

Don't forget to add the 's' (Contacts) at the end of the child object.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .