Sub topic 12
Reading related data with SOQL
This chapter assumes you know basic SOQL SELECT syntax, can find relationship fields in Object Manager, and have read the earlier chapters on lookup, master-detail, and junction objects. It covers the two directions of a relationship query and how to reach data through a junction object.
Two directions, two syntaxes
A relationship field gives you two ways to read data, depending on where you start.
- Child-to-parent: you start at the child object and follow the relationship field up to the parent. You use dot notation.
- Parent-to-child: you start at the parent object and pull in its children. You use a subquery in parentheses.
Child-to-parent: dot notation
On the child, the relationship field name ends in Id for standard objects (AccountId) or __c for custom ones. To walk up to the parent, you use the relationship name. For a standard field, drop Id. For a custom field, replace __c with __r.
SELECT Id, LastName, Account.Name
FROM Contact
WHERE Account.Industry = 'Technology'Account.Name reads a field on the parent. Account.Industry filters on a parent field. You can go up several levels, such as Account.Owner.Name, up to five levels.
Parent-to-child: subqueries
To start from the parent, you add a subquery in the SELECT list. The subquery uses the child relationship name, which is usually the plural form of the child object.
SELECT Name, (SELECT LastName FROM Contacts)
FROM AccountEach returned Account carries a list of its contacts. You can use WHERE, ORDER BY, and LIMIT inside the subquery. Accounts with no contacts are still returned, with an empty child list.
A custom relationship name needs the __r suffix. If a child relationship is named Enrollments, you query Enrollments__r.
Reading through a junction object
A many-to-many relationship has no direct field between the two masters. You reach the other side by going through the junction object. Assume Enrollment__c has master-detail fields to Course__c and Student__c, and the child relationship name on Course__c is Enrollments.
SELECT Name, (SELECT Student__r.Name FROM Enrollments__r)
FROM Course__c
WHERE Name = 'Apex Basics'This query combines both directions. The subquery goes down from the course to its junction records. Then Student__r.Name goes up from each junction record to the student. The result is the list of students enrolled in one course.
To reverse it, start at Student__c and use the child relationship name defined on the Student__c master-detail field.
Common errors
- Wrong name in a subquery. The
FROMclause of a subquery takes the child relationship name, not the child object name.FROM Contactsworks forAccount.FROM Contactfails. - Wrong suffix. A custom relationship needs
__rin queries. Using__creturns the Id, not the parent record. - Relationship name mismatch. The name you set in the field definition decides what you write in the query. If a query reports an invalid relationship, check the field's child relationship name in Object Manager.
- Treating the subquery result as a field. In Apex, the child list is a nested list on each parent record, not a flat value.
- Counting children on a lookup. Lookup relationships cannot have a native roll-up summary field. Use an aggregate query instead.
Set<Id> accountIds = new Set<Id>{ '001000000000001AAA' };
List<AggregateResult> totals = [
SELECT AccountId, COUNT(Id) total
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
];The Id above is a placeholder. Replace it with real account Ids before you run this.
Exercise
A custom master-detail field Course__c on Enrollment__c has the relationship name Enrollments. Write the part of a query on Course__c that selects each enrollment's Name, and state which suffix and name form you use.
Show answer
Use a subquery in the SELECT list on the child relationship name with the _r suffix: `SELECT Name, (SELECT Name FROM Enrollmentsr) FROM Coursec. The subquery's FROM takes the child relationship name, not the object name Enrollment_c`.
Exercise
In a query on Contact, how do you filter on the industry of the contact's account, and why can't you do the same on a many-to-many relationship directly from one master to the other?
Show answer
Use dot notation: WHERE Account.Industry = 'Technology'. A many-to-many relationship has no field linking the two masters. You must go through the junction object, using a subquery on one master and dot notation to the other master from the junction records.