Sub topic 7
Using WHERE, ORDER BY, and LIMIT inside a subquery
This chapter assumes you can write a basic SOQL query with SELECT, FROM, WHERE, ORDER BY, and LIMIT. It also assumes you know the child relationship name of a parent-to-child subquery, such as Contacts on Account or Tasks__r on a custom object. Basic Apex syntax is enough for the code at the end.
A subquery in the SELECT list is a small query of its own. It accepts its own WHERE, ORDER BY, and LIMIT clauses, and those clauses affect only the child rows it returns. The outer query's clauses affect only the parent rows. Most mistakes with these queries come from mixing up which clauses apply to which level.
The subquery is its own query
Here is the parent-to-child query from earlier chapters, with all three clauses added to the subquery:
SELECT Id, Name,
(SELECT Id, LastName
FROM Contacts
WHERE Email != null
ORDER BY LastName
LIMIT 5)
FROM Account
WHERE Industry = 'Technology'
ORDER BY Name
LIMIT 20The query returns two kinds of clause:
| Clause | Written where | What it controls |
|---|---|---|
| `WHERE Industry = 'Technology'` | Outer query | Which accounts come back |
| `ORDER BY Name` | Outer query | The order of the accounts |
| `LIMIT 20` | Outer query | The maximum number of accounts |
| `WHERE Email != null` | Subquery | Which contacts are attached to each account |
| `ORDER BY LastName` | Subquery | The order of the contacts inside each account |
| `LIMIT 5` | Subquery | The maximum number of contacts attached to each account |
Within the subquery, you write FROM Contacts, using the child relationship name, not the object name Contact. Everything else follows the normal SOQL rules for a query on Contact.
A working model of evaluation
It helps to picture the query running in two steps. The first step finds the parents. The second step builds a child list for each parent that was found.
This is a model for reasoning about results. The platform may run the query differently internally, but the results match this picture.
WHERE inside the subquery filters children only
The most common surprise is that a subquery WHERE never removes a parent. Consider this query:
SELECT Id, Name,
(SELECT Id, LastName FROM Contacts WHERE Email != null)
FROM Account
WHERE Industry = 'Technology'Every Technology account is returned. An account with no contacts, or with no contacts that have an email address, still appears. Its child list is simply empty. If you want to return only the accounts that have a matching contact, you need a semi-join in the outer WHERE, which a later chapter covers in detail. A preview looks like this:
SELECT Id, Name,
(SELECT Id, LastName
FROM Contacts
WHERE Email != null
ORDER BY LastName
LIMIT 5)
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact WHERE Email != null)The semi-join restricts the parents. The subquery WHERE restricts the children. You usually repeat the same condition in both places so the two agree.
What you can use in a subquery WHERE
The subquery WHERE can use the fields of the child object, and it can follow the child's own parent relationships. For example, you can filter contacts by a field on their account:
SELECT Id, Name,
(SELECT Id, LastName
FROM Contacts
WHERE Account.Industry = 'Technology' AND Department = 'Engineering')
FROM AccountIn Apex, a subquery WHERE can also use bind variables, written with a colon, such as :minAmount. The next sections use that form.
ORDER BY inside the subquery sorts each child list
A subquery ORDER BY sorts the children within each parent. It does not change the order of the parents. If you want the accounts in a specific order, put an ORDER BY on the outer query as well.
SELECT Id, Name,
(SELECT Id, Name, Amount
FROM Opportunities
ORDER BY Amount DESC NULLS LAST)
FROM Account
ORDER BY NameThe accounts are sorted by name, and each account's opportunities are sorted from largest to smallest amount. NULLS LAST keeps opportunities with no amount at the end of each list. Without an ORDER BY, SOQL makes no promise about the order of rows. Do not depend on the order you happen to see in a default query.
LIMIT inside the subquery applies per parent
A subquery LIMIT caps the children for each parent separately. It is not a cap on the total number of child rows across the whole query.
SELECT Id, Name,
(SELECT Id, LastName FROM Contacts ORDER BY LastName LIMIT 5)
FROM Account
WHERE Industry = 'Technology'
LIMIT 10This query returns up to 10 accounts, and each account carries up to 5 contacts. The most contact rows you can get back is 50. This is a convenient way to get "the top N children for each parent" in one query.
Limits still count rows
Child rows returned by subqueries count toward the total number of rows a query may retrieve. In Apex, they also count toward the governor limit on rows returned by SOQL queries in a transaction. A query with 200 parents and no subquery LIMIT can return many thousands of contacts, so a subquery LIMIT is also a way to protect your transaction limits.
There are further structural limits. A single query may contain only a limited number of parent-to-child subqueries (20 at the time of writing). Check the current SOQL limits documentation for your API version, because these numbers can change.
Putting it together in Apex
The following anonymous Apex block runs a query with a bind variable in the subquery, a sorted and limited child list, and a sorted and limited parent list. It then reads the results.
Decimal minAmount = 10000;
List<Account> accounts = [
SELECT Id, Name,
(SELECT Name, Amount
FROM Opportunities
WHERE StageName = 'Closed Won' AND Amount >= :minAmount
ORDER BY Amount DESC
LIMIT 3)
FROM Account
WHERE Industry = 'Technology'
ORDER BY Name
LIMIT 10
];
for (Account a : accounts) {
List<Opportunity> topDeals = a.Opportunities;
if (topDeals == null || topDeals.isEmpty()) {
System.debug(a.Name + ': no qualifying deals');
continue;
}
System.debug(a.Name + ': ' + topDeals.size() + ' deal(s)');
for (Opportunity o : topDeals) {
System.debug(' ' + o.Name + ' - ' + o.Amount);
}
}The loop handles accounts that have no qualifying opportunities, which is normal because the subquery WHERE does not remove parents. The code treats the child list as possibly missing and checks null as well as isEmpty(), so an account with no matches cannot cause a null-reference error.
Custom objects follow the same rules
Nothing changes for custom relationships except the name. The child relationship name ends in __r:
SELECT Id, Name,
(SELECT Id, Name, Due_Date__c
FROM Tasks__r
WHERE Is_Complete__c = false
ORDER BY Due_Date__c
LIMIT 3)
FROM Project__c
WHERE Status__c = 'Active'This returns the active projects, each with its three earliest open tasks. The field names Due_Date__c and Is_Complete__c are examples. Use the API names from your own org.
Common mistakes
- Expecting the subquery WHERE to remove parents. It only trims the child list. Use a semi-join (
WHERE Id IN (...)) on the outer query to restrict parents. - Expecting the subquery LIMIT to be a global cap. It applies to each parent. Ten parents with
LIMIT 5can return up to 50 child rows. - Using the object name in the subquery FROM. Write
FROM Contacts, notFROM Contact, and use the__rname for custom relationships. - Forgetting the outer ORDER BY. The subquery ORDER BY sorts only the children.
- Sorting nothing, then limiting. A LIMIT with no ORDER BY returns an unpredictable set of children.
- Assuming every parent has a child list with items. Check for an empty or missing list before reading from it.
Exercise
You run this query and 40 Technology accounts exist. Of those, 12 have no contact with an email address. How many accounts does the query return, and what does an account with no email contacts carry? SELECT Id, Name, (SELECT Id, LastName FROM Contacts WHERE Email != null ORDER BY LastName LIMIT 3) FROM Account WHERE Industry = 'Technology'
Show answer
It returns all 40 accounts, because the subquery WHERE only filters contacts and never removes parents. The 12 accounts without email contacts carry an empty child list. Each of the other accounts carries up to 3 contacts, sorted by last name.
Exercise
Rewrite the query from the previous exercise so it returns only the accounts that have at least one contact with an email address, still showing up to three of those contacts sorted by last name.
Show answer
SELECT Id, Name, (SELECT Id, LastName FROM Contacts WHERE Email != null ORDER BY LastName LIMIT 3) FROM Account WHERE Industry = 'Technology' AND Id IN (SELECT AccountId FROM Contact WHERE Email != null)