Sub topic 6
Parent-to-child: subqueries in the SELECT list
A parent-to-child query returns parent records and, for each parent, a list of its related child records. You write it by placing a subquery in the SELECT list of the outer query. This chapter assumes you can write basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT) and that you know the difference between lookup and master-detail relationships. It also assumes you know what a child relationship name is, which the earlier chapter on relationship names covered.
What a parent-to-child query does
A child-to-parent query starts at the "many" side and reaches up with dot notation. A parent-to-child query starts at the "one" side and pulls down the related rows. Here is the first example.
SELECT Id, Name,
(SELECT Id, LastName FROM Contacts ORDER BY LastName LIMIT 5)
FROM Account
WHERE Industry = 'Technology'The query has two parts:
- The outer query runs against
Account. ItsWHEREclause decides which accounts come back. - The inner query sits in parentheses in the SELECT list. It runs once for each returned account and returns that account's contacts.
The result is one row per account. Each row carries a nested list of contact records. The result is not a flat table, so you do not get one row per account-contact pair as you would with a SQL join.
The FROM clause takes a relationship name
The most common mistake in this kind of query is the name used in the subquery's FROM clause. A normal query names an object, such as FROM Contact. A subquery names the child relationship, such as FROM Contacts. The two names often differ.
| Parent | Child object | Name in the subquery FROM |
|---|---|---|
| Account | Contact | `Contacts` |
| Account | Opportunity | `Opportunities` |
| Account | Case | `Cases` |
| Opportunity | OpportunityLineItem | `OpportunityLineItems` |
| `Project__c` | `Task__c` | `Tasks__r` (set on the field) |
For standard relationships the name is usually the plural of the child object. Custom relationships use the Child Relationship Name you chose when you created the lookup or master-detail field, plus the __r suffix. Here is the custom-object example from the plan.
SELECT Id, Name,
(SELECT Id, Name FROM Tasks__r)
FROM Project__cTasks__r exists only because the lookup field on Task__c pointing at Project__c was given the child relationship name Tasks. If the field had been created with a different name, the subquery would use that name instead.
Finding the right name
Do not guess. Use one of these sources:
- In Setup, open Object Manager, choose the child object, open the lookup or master-detail field, and read the Child Relationship Name value.
- Run a describe call in Apex and list the child relationships of the parent.
- Open the parent object's schema in a tool such as Workbench or the VS Code Salesforce extension and read the relationship names.
This anonymous Apex lists every child relationship name for Account.
Schema.DescribeSObjectResult describe = Account.SObjectType.getDescribe();
for (Schema.ChildRelationship rel : describe.getChildRelationships()) {
if (rel.getRelationshipName() != null) {
System.debug(rel.getRelationshipName() + ' -> ' + rel.getChildSObject());
}
}Some child relationships have a null name and cannot be queried with a subquery. The if check skips them.
Parents without children still appear
A parent-to-child subquery behaves like a left outer join. An account with no contacts is still returned, and its Contacts list is empty. This differs from filtering with a dot-notation WHERE clause on a child-to-parent query, where the filter decides which child rows are returned.
If you want only the parents that have at least one matching child, a subquery in the SELECT list cannot do that. Use a semi-join in the WHERE clause. A later chapter covers semi-joins.
SELECT Id, Name,
(SELECT Id, LastName FROM Contacts WHERE Email != null)
FROM AccountIn this query, the WHERE inside the subquery filters only the contacts. Every account is still returned, and accounts with no contact that has an email address get an empty list.
Clauses inside the subquery
The subquery is a small query of its own. You can give it WHERE, ORDER BY, and LIMIT, and they apply to the child rows for each parent separately. In the first example, LIMIT 5 returns up to five contacts per account, not five contacts overall. Clauses on the outer query apply only to the parents.
The next chapter covers these clauses in detail. For now, remember the scope rule: clauses inside the parentheses control the children, and clauses outside control the parents.
Reading the results in Apex
In Apex, the child records are stored on the parent record under the relationship name. The value is a List of the child sObject type. This example uses the plan's code.
for (Account a : [SELECT Id, Name, (SELECT LastName FROM Contacts) FROM Account LIMIT 10]) {
System.debug(a.Name + ' has ' + a.Contacts.size() + ' contacts');
for (Contact c : a.Contacts) {
System.debug(c.LastName);
}
}Three details matter here:
a.Contactsis never null when the query includes the subquery. A parent with no children gets an empty list, sosize()returns 0 and the inner loop simply does not run.- The field name on the parent is the relationship name, with the same capitalization pattern as in the query. For a custom relationship, you read
p.Tasks__r. - If you did not include the subquery in the SELECT list, the relationship field is not loaded. Reading it then throws a
System.SObjectExceptionsaying the field was not queried. Add the subquery to the query rather than checking for null.
For a custom parent, the code looks the same, with the __r name.
for (Project__c p : [SELECT Id, Name, (SELECT Id, Name FROM Tasks__r) FROM Project__c]) {
System.debug(p.Name + ': ' + p.Tasks__r.size() + ' tasks');
}The chapter on reading results in Apex covers null handling and the child-to-parent direction in more depth.
Limits that affect subqueries
Subqueries share the limits of the query that contains them. The ones you are most likely to hit are these:
- Row limits. Child rows count toward the total rows retrieved by SOQL in a transaction, which is 50,000 in Apex. An outer query that returns 1,000 accounts with 60 contacts each retrieves 61,000 rows (the accounts plus the contacts) and fails. A
LIMITinside the subquery caps this. - Number of subqueries. One query can include up to 20 parent-to-child relationships in its SELECT list.
- Depth. In API version 58.0 and later, a query can nest parent-to-child subqueries up to five levels deep. In earlier versions, you can go down only one level from the outer query. Check your API version if a nested subquery fails.
- SOQL query count. The whole statement, subqueries included, counts as one SOQL query against the limit of 100 per synchronous transaction. This is a reason to prefer one subquery over a loop that runs a query per parent.
Deep nesting makes the result harder to read and process. Use it only when you need it.
Common errors
| Error message or symptom | Likely cause | Fix |
|---|---|---|
| `Didn't understand relationship 'Contact' in FROM part of query call` | The subquery used the object name instead of the relationship name | Use `Contacts` |
| The same error on a custom object | Wrote `Task__c` or `Tasks__c` instead of `Tasks__r` | Use the child relationship name plus `__r` |
| `No such column 'Contacts' on entity 'Contact'` | The subquery was placed in a query on the wrong object | Put the subquery in a query on the parent |
| `SObjectException: SObject row was retrieved via SOQL without querying the requested field` | Read `a.Contacts` without including the subquery | Add the subquery to the SELECT list |
| `Too many query rows: 50001` | The subquery returned many children per parent | Add `WHERE` or `LIMIT` inside the subquery, or filter the parents |
Choosing between the two directions
If you only need data from the child object and a few parent fields, a child-to-parent query is simpler. It returns flat rows and avoids nested lists. Choose parent-to-child when you need the parent as the unit of work, for example to process each account together with its contacts. It also suits cases where parent fields would otherwise repeat on every child row.
A parent-to-child query also keeps the "which parents" decision separate from the "which children" decision, and each side has its own WHERE clause.
Exercise
A developer writes SELECT Id, Name, (SELECT Id, Name FROM Task__c) FROM Project__c and gets an error. The lookup field on Task__c that points to Project__c has the child relationship name Tasks. What is the corrected query, and how would you read the child names in Apex for one project record p?
Show answer
The subquery must use the relationship name, not the object name: SELECT Id, Name, (SELECT Id, Name FROM Tasks__r) FROM Project__c. In Apex, read the children from p.Tasks__r, which is a list of Task__c records, so for (Task__c t : p.Tasks__r) { System.debug(t.Name); } works. Because the subquery is in the SELECT list, the list is empty (not null) for projects with no tasks.