Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.

Understanding Foreign Key and Parent-Child Relationship SOQL Queries

The SELECT statement of a SOQL query can be any valid SOQL statement, including foreign key and parent-child record joins. If foreign key joins are included, the resulting sObjects can be referenced using normal field notation. For example:

1System.debug([SELECT Account.Name FROM Contact
2              WHERE FirstName = 'Caroline'].Account.Name);

Additionally, parent-child relationships in sObjects act as SOQL queries as well. For example:

1for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts)
2                  FROM Account
3                  WHERE Name = 'Acme']) {
4     Contact[] cons = a.Contacts;
5}
6
7//The following example also works because we limit to only 1 contact
8for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts LIMIT 1)
9                  FROM Account
10                  WHERE Name = 'testAgg']) {
11     Contact c = a.Contacts;
12}