Sub topic 7
Using WHERE, ORDER BY, and LIMIT inside a subquery
This chapter assumes you can write basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT) and that you know how to write a parent-to-child subquery using the child relationship name, such as Contacts on Account. Here you will see how to shape the child rows that a subquery returns.
Two queries in one
A parent-to-child query has an outer query on the parent and an inner query on the children. Each part has its own clauses. A clause written inside the parentheses applies only to the child rows. A clause written after the subquery applies only to the parent rows.
SELECT Id, Name,
(SELECT Id, LastName FROM Contacts ORDER BY LastName LIMIT 5)
FROM Account
WHERE Industry = 'Technology'In this query:
WHERE Industry = 'Technology'selects which accounts come back.ORDER BY LastNamesorts the contacts inside each account.LIMIT 5returns at most five contacts for each account. It does not limit the total across all accounts.
Filtering child rows with WHERE
Add a WHERE clause inside the subquery to keep only some children.
SELECT Id, Name,
(SELECT Id, LastName FROM Contacts WHERE Email != null)
FROM Account
WHERE Industry = 'Technology'Every technology account is still returned. An account with no matching contacts comes back with an empty child list. If you want to drop those accounts, you must filter the parent, for example with a semi-join (covered in a later chapter).
Sorting and limiting children
The ORDER BY in a subquery sorts the children within each parent. The order of the parents themselves is set only by an ORDER BY after the subquery.
SELECT Id, Name,
(SELECT Id, LastName, CreatedDate
FROM Contacts
ORDER BY CreatedDate DESC
LIMIT 3)
FROM Account
WHERE Industry = 'Technology'
ORDER BY Name
LIMIT 10This returns up to 10 accounts sorted by name. Each account carries its three newest contacts. The pattern "latest N children per parent" is a common use of this form.
Using the same pattern on custom objects
The clauses work the same way for custom relationships. Use the child relationship name, which ends in __r.
SELECT Id, Name,
(SELECT Id, Name FROM Tasks__r WHERE Name LIKE 'Review%' ORDER BY Name)
FROM Project__cCommon mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Expecting the subquery `LIMIT` to cap the total child rows | Each parent gets its own cap | Query the child object directly if you need a global cap |
| Putting a child filter in the outer WHERE | The filter applies to the parent fields, or the query fails | Move it inside the parentheses |
| Expecting parents with no matching children to disappear | They are still returned with an empty list | Add a semi-join on the parent |
| Using the object name in the subquery FROM | Query error | Use the child relationship name |
Reading the filtered result in Apex
The filtered child list is available through the relationship name on each parent. Because of the subquery's WHERE clause, the list can be empty, so loop over it instead of reading a fixed index.
for (Account a : [SELECT Id, Name,
(SELECT LastName FROM Contacts WHERE Email != null ORDER BY LastName LIMIT 5)
FROM Account
WHERE Industry = 'Technology'
LIMIT 10]) {
System.debug(a.Name + ' has ' + a.Contacts.size() + ' matching contacts');
for (Contact c : a.Contacts) {
System.debug(c.LastName);
}
}Exercise
A query returns accounts with the subquery (SELECT Id FROM Contacts ORDER BY CreatedDate DESC LIMIT 1). The outer query matches 8 accounts. What is the largest number of contact rows the subquery can return in total, and what does an account with no contacts return?
Show answer
At most 8 contact rows, because the LIMIT of 1 applies to each account separately. An account with no contacts is still returned, with an empty child list.
Exercise
You want only accounts that have at least one contact with an email address, and for each of those accounts you want only the contacts with an email address. Where does the email filter go?
Show answer
In two places. Put WHERE Email != null inside the subquery to filter the child rows. Also filter the parent with a semi-join: WHERE Id IN (SELECT AccountId FROM Contact WHERE Email != null).