Sub topic 12
Reading related data with SOQL
This chapter assumes you know basic SOQL SELECT syntax and can find fields in the Object Manager. It also assumes you have created lookup and master-detail fields, and the Course, Student, and Enrollment junction model from the previous chapters. Here you will learn the two directions a query can travel across a relationship, how relationship names are built, and which mistakes cause errors or silently missing rows.
Two directions, two syntaxes
SOQL has no JOIN keyword. Salesforce already knows how objects are related, so you traverse a relationship by name. The syntax depends on which way you travel.
- Child-to-parent: you start at the child (the object holding the relationship field) and use dot notation to reach parent fields.
- Parent-to-child: you start at the parent and write a subquery in the
SELECTlist to return the child records.
Relationship names
The names you write in a query are not the field API names. Each relationship field produces two names.
| Direction | Standard example | Custom example |
|---|---|---|
| Child-to-parent (the field's relationship name) | `Account` (from `AccountId`) | `Student__r` (from `Student__c`) |
| Parent-to-child (the child relationship name) | `Contacts` | `Enrollments__r` |
For a standard lookup, you drop Id from the field name. For a custom field, you replace __c with __r. The child relationship name for a custom field comes from the Child Relationship Name you set when you created the field. In the metadata file for Enrollment__c.Course__c, that is <relationshipName>Enrollments</relationshipName>. In SOQL, Salesforce appends __r, so you write Enrollments__r.
You can look up the exact names in the Object Manager, on the field's detail page. You can also run describe on the sObject in Apex.
Child-to-parent queries
Start at the child and traverse upward with dots.
SELECT Id, LastName, Account.Name
FROM Contact
WHERE Account.Industry = 'Technology'The parent fields can appear in SELECT, WHERE, and ORDER BY. You can traverse several levels, such as Contact.Account.Owner.Name, up to five levels of parent. A single query can include at most 55 child-to-parent relationships.
What happens when the parent is empty
A lookup field is optional, so some children have no parent. These two clauses behave differently:
- In the
SELECTlist, a missing parent does not remove the row. The parent field simply comes back asnull. - In the
WHEREclause, a condition on a parent field such asAccount.Industry = 'Technology'can only be true when a parent exists. Contacts with no account are excluded.
Master-detail fields are always populated, so this only matters for lookups. In Apex, reading a field through a missing parent throws a NullPointerException.
Contact c = [SELECT Id, LastName, Account.Name FROM Contact LIMIT 1];
// Throws NullPointerException when the contact has no account:
// String name = c.Account.Name;
// Safe navigation returns null instead:
String name = c.Account?.Name;
System.debug(name);Parent-to-child queries
Start at the parent and add a subquery in the SELECT list. The FROM clause of the subquery uses the child relationship name, not the object name.
SELECT Name, (SELECT LastName FROM Contacts)
FROM AccountEach returned account carries a nested list of its contacts. Accounts with no contacts are still returned, and their list is empty.
In Apex, the nested list is available as a property named after the relationship:
List<Account> accounts = [
SELECT Name, (SELECT LastName FROM Contacts)
FROM Account
LIMIT 10
];
for (Account a : accounts) {
System.debug(a.Name + ' has ' + a.Contacts.size() + ' contacts');
for (Contact c : a.Contacts) {
System.debug(' ' + c.LastName);
}
}Subqueries accept their own WHERE, ORDER BY, and LIMIT. This returns only each account's three most recently created contacts:
SELECT Name,
(SELECT LastName FROM Contacts ORDER BY CreatedDate DESC LIMIT 3)
FROM Account
WHERE Industry = 'Technology'Limits to remember
- A query can contain at most 20 parent-to-child subqueries.
- Subquery rows count toward the total number of rows retrieved in the transaction, along with the parent rows.
- You cannot use aggregate functions such as
COUNT()inside the subquery to get a count per parent. Use an aggregate query instead, covered below.
Querying a many-to-many relationship
A junction object has two master-detail fields, so you can read the relationship from either parent. Both query shapes below assume Enrollment__c has Course__c and Student__c, and that both fields use the child relationship name Enrollments.
To list the students of one course, go parent-to-child to the junction records, then child-to-parent from each junction record to the other parent:
SELECT Name, (SELECT Student__r.Name FROM Enrollments__r)
FROM Course__c
WHERE Name = 'Apex Basics'The same pattern works from the other side. This lists each student's courses:
SELECT Name, (SELECT Course__r.Name FROM Enrollments__r)
FROM Student__cOr you can query the junction object directly. This returns one flat row per pairing and is often easier to process:
SELECT Course__r.Name, Student__r.Name
FROM Enrollment__c
ORDER BY Course__r.NameQuerying the junction object directly is also the best choice when you want fields stored on the junction itself, such as an enrollment date or a grade.
Filtering by related records: semi-joins and anti-joins
Dot notation and subqueries in SELECT return related data. To filter parents by their children, put a subquery in the WHERE clause with IN or NOT IN.
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact WHERE LastName LIKE 'A%')This is a semi-join. It returns accounts that have at least one contact whose last name starts with A, and it does not return the contacts. Using NOT IN gives an anti-join, such as accounts with no contacts:
SELECT Id, Name
FROM Account
WHERE Id NOT IN (SELECT AccountId FROM Contact)The same idea finds courses nobody has enrolled in:
SELECT Id, Name
FROM Course__c
WHERE Id NOT IN (SELECT Course__c FROM Enrollment__c)Note that the subquery here selects the field Course__c (an Id), not the relationship name. Semi-joins compare Ids, so you select the relationship field itself.
Counting children without a roll-up summary field
Roll-up summary fields exist only on the master side of a master-detail relationship. For a lookup, you can compute totals at query time with an aggregate query that groups by the parent Id.
Set<Id> accountIds = new Set<Id>{ '001000000000001AAA' };
List<AggregateResult> totals = [
SELECT AccountId, COUNT(Id) total
FROM Contact
WHERE AccountId IN :accountIds
GROUP BY AccountId
];
for (AggregateResult ar : totals) {
System.debug(ar.get('AccountId') + ' -> ' + ar.get('total'));
}The Id in this example is a placeholder, so replace it with a real account Id. Aggregate results come back as AggregateResult objects, and you read each value with get() using the field name or the alias (total). Parents with zero children do not appear in the results. Treat a missing parent as a count of zero in your code.
Polymorphic relationships
Some relationship fields can point to more than one object type. Examples are Owner (a User or a Queue on some objects), Task.WhatId, and Task.WhoId. You can read fields that exist on all target types, such as Owner.Name. To read type-specific fields, use TYPEOF:
SELECT Id, Subject,
TYPEOF What
WHEN Account THEN Name, Industry
WHEN Opportunity THEN Name, StageName
END
FROM TaskCustom lookup fields point to exactly one object, so polymorphism is a concern mainly on standard fields like these.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| `Didn't understand relationship 'Enrollment__c' in FROM part of query` | The subquery used the object name, not the child relationship name | Use `Enrollments__r` |
| `No such column 'Course__r' on entity` | Wrong direction, or a typo in the relationship name | Check the names in Object Manager |
| `NullPointerException` in Apex | A lookup parent is empty and you dereferenced it | Use `?.` or check for `null` first |
| Fewer rows than expected | A `WHERE` condition on a parent field excluded children with no parent | Filter on the parent Id or restructure the query |
| Parent missing from aggregate results | The parent has no children | Default the count to 0 in code |
Exercise
Exercise
Enrollment_c has master-detail fields Coursec and Student_c, and the child relationship name on both is Enrollments. Write one SOQL query that returns every course name together with the names of its enrolled students, and a second query that returns only the courses that have no enrollments.
Show answer
First query: SELECT Name, (SELECT Student_r.Name FROM Enrollmentsr) FROM Coursec. The subquery uses the child relationship name Enrollmentsr, and Studentr.Name reads the Name field on the other parent through dot notation. Second query: SELECT Id, Name FROM Coursec WHERE Id NOT IN (SELECT Coursec FROM Enrollmentc). This is an anti-join, and the subquery selects the Id field Coursec rather than the relationship name Course_r.
Exercise
A Contact has no Account. What does SELECT LastName, Account.Name FROM Contact return for that contact, and what happens if you add WHERE Account.Name != 'Acme'?
Show answer
Without the WHERE clause, the contact is returned and Account.Name is null. With the WHERE clause, the contact is excluded, because a condition on a parent field cannot be satisfied when no parent exists. In Apex, reading c.Account.Name for that contact throws a NullPointerException unless you use safe navigation (c.Account?.Name).