Sub topic 13
Limits and common mistakes
This chapter covers the limits that apply to relationship queries and the errors that come up most often. It assumes you can write basic SOQL (SELECT, WHERE, ORDER BY, LIMIT) and read basic Apex. It also assumes you know the earlier chapters' material on lookup and master-detail relationships, relationship names, dot notation, and subqueries.
Limits that apply to relationship queries
Relationship queries are limited in two ways. SOQL has its own structural rules, and Apex governor limits apply when the query runs in a transaction.
Structural limits
| Limit | Value | Notes |
|---|---|---|
| Child-to-parent levels in one path | 5 | `Contact.Account.Owner.Manager.Manager.Name` is the deepest path allowed. |
| Child-to-parent relationships in one query | 55 | Each distinct relationship you traverse counts. |
| Parent-to-child subqueries in one query | 20 | Each subquery in the `SELECT` list counts. |
| Parent-to-child nesting depth | 5 levels in API version 58.0 and later; 1 level in earlier versions | Check the API version of your Apex class or API call. |
Treat these numbers as ceilings you check against the current Salesforce documentation. Most real queries hit a different limit first, which is the row count.
Governor limits in Apex
A query with subqueries is still one query. It counts once against the limit of 100 SOQL queries in a synchronous transaction. The records it returns are counted differently:
- Parent rows count toward the limit of 50,000 rows retrieved by SOQL in a transaction.
- Child rows returned by subqueries also count toward that 50,000.
A query that returns 200 accounts with 300 contacts each uses 60,200 rows and fails. This surprises people because the query looks like it returns only 200 records.
// Fails with "Too many query rows: 50001" if the data is large enough.
List<Account> accounts = [
SELECT Id, (SELECT Id FROM Contacts)
FROM Account
LIMIT 200
];Two ways to stay under the limit are to cap the children with LIMIT inside the subquery, and to select only the fields you use. You can also query the child object directly with a filter that bounds the result.
What a single result can hold
The two directions have different cost profiles:
- A child-to-parent query returns one row per child. The parent fields repeat on each row but add no extra rows to the count.
- A parent-to-child query returns one row per parent plus every child row. The total can be far larger than the parent count.
Restrictions on semi-joins and anti-joins
The IN and NOT IN subqueries from the earlier chapter are stricter than parent-to-child subqueries. The common restrictions are:
- The subquery must select a single field, and that field must be an ID or a foreign key. It cannot traverse a relationship.
- The subquery cannot use
ORDER BY,LIMIT, orOFFSET. - The subquery cannot contain its own subquery in its
SELECTlist. - The semi-join condition cannot be joined to other conditions with
OR.
This query breaks the first rule because the selected field traverses a relationship:
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT Account.Id FROM Contact)The fix is to select the foreign key itself, as in the earlier example:
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact)If you need OR, run two queries and merge the results in Apex. Alternatively, express the condition as a filter on a field of the parent record.
Naming mistakes
The most common error is using the wrong name for the relationship. Each relationship has two names that look alike:
| You want | Wrong | Right |
|---|---|---|
| The parent of a custom lookup `Project__c` | `Project__c.Name` | `Project__r.Name` |
| The children of `Account` | `FROM Contact` inside the subquery's parent-side name | `(SELECT Id FROM Contacts)` |
| The children via a custom field | `Task__c` as the subquery name | `Tasks__r`, the child relationship name set on the field |
| The parent of a standard lookup | `AccountId.Name` | `Account.Name` |
A good habit is to look up the name rather than guess. In Setup, open the object, find the lookup or master-detail field, and read its child relationship name. You can also read it in Apex.
Schema.DescribeSObjectResult accountDescribe = Account.SObjectType.getDescribe();
for (Schema.ChildRelationship rel : accountDescribe.getChildRelationships()) {
if (rel.getRelationshipName() != null) {
System.debug(rel.getChildSObject() + ' via ' + rel.getRelationshipName());
}
}The error messages tell you what went wrong:
Didn't understand relationship 'X' in FROM part of query callmeans the child relationship name in a subquery is wrong.No such column 'X' on entity 'Y'means a relationship or field name is wrong, or you lack access to it.
Apex access mistakes
The query can be correct and the code that reads it can still fail. Three errors account for most of these cases.
Null parents
If a lookup field is empty, the parent sObject is null. Reading a field from it throws System.NullPointerException.
Contact c = [SELECT Id, Account.Name FROM Contact WHERE AccountId = null LIMIT 1];
// c.Account is null here, so this line would throw:
// String name = c.Account.Name;
String safeName = c.Account?.Name;
System.debug(safeName); // nullMaster-detail parents are always present, so this mostly affects lookups. Do not assume a lookup is filled in just because your test data fills it.
Fields you did not query
Apex only holds the fields listed in the SELECT. Reading anything else throws System.SObjectException: SObject row was retrieved via SOQL without querying the requested field. This also applies to parent fields:
Contact c = [SELECT Id, Account.Name FROM Contact LIMIT 1];
// Throws SObjectException: Account.Industry was not queried.
// String industry = c.Account.Industry;Add Account.Industry to the query, or query it separately when you need it.
Child lists
When the subquery is in the SELECT list, the child relationship returns a list. An account with no matching children gets an empty list, so size() and loops work without a null check. When the subquery is missing from the SELECT, accessing the relationship throws an exception instead.
Aggregate and polymorphic mistakes
Grouping by name instead of ID
This query from earlier in the tutorial runs, but it can mislead:
SELECT Account.Name, COUNT(Id)
FROM Contact
GROUP BY Account.NameTwo different accounts named "Acme" fall into one group. Group by the ID and add the name as a second group field when you need to display it:
SELECT AccountId, Account.Name, COUNT(Id)
FROM Contact
GROUP BY AccountId, Account.NameIn Apex, each row of an aggregate query is an AggregateResult, and you read values with get('fieldAlias'). Unnamed aggregates get aliases such as expr0, so name them when you can:
for (AggregateResult ar : [
SELECT AccountId acctId, COUNT(Id) total
FROM Contact
WHERE AccountId != null
GROUP BY AccountId
]) {
System.debug(ar.get('acctId') + ': ' + ar.get('total'));
}Subqueries in aggregate queries
You cannot put a parent-to-child subquery in a query that uses GROUP BY. If you need both counts and child detail, run two queries.
Polymorphic fields
Fields such as Owner, What, and Who can point to more than one object type. A path like Owner.Name works because Name exists on every possible type. A field that exists on only some types, such as What.Amount, fails. Use TYPEOF for those cases, and remember that the fields in each WHEN branch must exist on that object.
Choosing a direction
Pick the direction by what you need back, not by which object you started from.
Some rules of thumb follow from the limits above:
- If you only need a few parent fields per child, query the child object and use dot notation. This costs one row per child and keeps the row count predictable.
- If you need the children grouped under each parent, use a subquery and put a
LIMITin it. - If you only want parents that have or lack children, use a semi-join or anti-join. This avoids returning child rows at all.
- If the number of children may exceed what a transaction can hold, query the child object with a filter on the parent IDs, and process the results in batches.
Avoiding queries in loops
A frequent mistake is running a query per record in a loop. Each query counts against the 100-query limit. The fix is to collect IDs first, run one query, and group the results in a map.
List<Account> accounts = [SELECT Id, Name FROM Account WHERE Industry = 'Technology' LIMIT 200];
Set<Id> accountIds = new Map<Id, Account>(accounts).keySet();
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for (Contact c : [SELECT Id, LastName, AccountId FROM Contact WHERE AccountId IN :accountIds]) {
if (!contactsByAccount.containsKey(c.AccountId)) {
contactsByAccount.put(c.AccountId, new List<Contact>());
}
contactsByAccount.get(c.AccountId).add(c);
}
for (Account a : accounts) {
List<Contact> contacts = contactsByAccount.containsKey(a.Id)
? contactsByAccount.get(a.Id)
: new List<Contact>();
System.debug(a.Name + ': ' + contacts.size());
}This is one extra query regardless of how many accounts there are. A parent-to-child subquery gives the same data in a single statement, but this version lets you filter or cap the children without the nesting restrictions.
Checklist before you ship a relationship query
- Every relationship name was copied from Setup or from a describe call, not guessed.
- Custom lookup paths use
__r, and child names for custom relationships use the name defined on the field. - Apex code handles a
nullparent with?.or an explicit check. - Every field read in Apex appears in the
SELECT. - Subqueries have a
LIMITwhen the child count is unbounded. - Semi-join subqueries select one ID field and use no
ORDER BY,LIMIT, orOR. - Aggregates group by ID, not by a name field.
- There are no queries inside loops.
Exercise
This query is meant to return each custom Task_c row with its project's name, but it fails with a "No such column" error. What is wrong, and what is the corrected query? SELECT Id, Name, Projectc.Name FROM Task_c
Show answer
Project_c is the lookup field, which holds the parent's ID. Dot notation needs the relationship name, which for a custom lookup ends in r. The corrected query is SELECT Id, Name, Projectr.Name FROM Task_c.
Exercise
An Apex method runs [SELECT Id, (SELECT Id FROM Contacts) FROM Account LIMIT 200] in a org where each account has about 400 contacts. It fails with "Too many query rows: 50001". Why does it fail even though only 200 accounts are selected, and give two ways to fix it.
Show answer
Contact rows returned by the subquery count toward the 50,000-row limit, in addition to the account rows. 200 accounts with 400 contacts each is 80,200 rows. Fixes: add a LIMIT inside the subquery to cap the children per account, or query Contact directly with WHERE AccountId IN :accountIds and process the accounts in smaller batches.
Exercise
Why does this semi-join fail, and how would you rewrite it? SELECT Id FROM Account WHERE Id IN (SELECT AccountId FROM Contact ORDER BY LastName LIMIT 10)
Show answer
Semi-join subqueries cannot use ORDER BY, LIMIT, or OFFSET. Remove them to get SELECT Id FROM Account WHERE Id IN (SELECT AccountId FROM Contact). If you need only ten specific contacts, query Contact first with the ORDER BY and LIMIT, collect their AccountId values in Apex, and use WHERE Id IN :accountIds in a second query.