Sub topic 4
Filtering and sorting on parent fields
This chapter assumes you can write basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT). It also assumes you know what a lookup field is and how a relationship name differs from a field name. You should already be able to select parent fields with dot notation, such as Account.Name on a Contact. Here you will use the same paths in WHERE and ORDER BY, and see how records with an empty lookup behave.
Parent fields work anywhere a field works
A relationship path like Account.Industry is not limited to the SELECT list. You can use it in WHERE and ORDER BY. You can also select it in a query that does not mention it elsewhere.
SELECT Id, LastName, Account.Name, Account.Owner.Name
FROM Contact
WHERE Account.Industry = 'Technology'
ORDER BY Account.NameThree things happen in this query:
- The
FROMobject is Contact, so each row returned is a Contact. WHERE Account.Industry = 'Technology'is evaluated against the parent Account of each Contact.ORDER BY Account.Namesorts the Contacts by their parent's name.
The filter on the parent does not change what a row is. You still get Contacts, not Accounts. Contacts from the same Account appear once each, and they are grouped together only because they share a sort key.
Filtering on parent fields
Any operator you can use on a child field works on a parent field, as long as the parent field itself is filterable.
SELECT Id, Name, Project__r.Name
FROM Task__c
WHERE Project__r.Status__c = 'Active'
AND Project__r.CreatedDate = LAST_N_DAYS:90The same rules apply as for any field:
- Use
=,!=,<,>,LIKE,IN, andINCLUDESaccording to the parent field's type. - Use date literals such as
LAST_N_DAYS:90on parent date fields. - Combine child and parent conditions freely with
AND,OR, andNOT.
SELECT Id, Name, Amount, Account.Name
FROM Opportunity
WHERE Amount > 50000
AND (Account.Industry = 'Technology' OR Account.BillingState = 'CA')For a custom lookup, use the relationship name with __r, not the field name that ends in __c. Project__r.Status__c is correct. Project__c.Status__c is an error, because Project__c holds an ID, not a record.
Bind variables in Apex
In Apex, parent-field filters accept bind variables like any other filter. The next example is complete. You can run it as anonymous Apex.
Set<String> industries = new Set<String>{ 'Technology', 'Finance' };
String namePrefix = 'A%';
List<Contact> contacts = [
SELECT Id, LastName, Account.Name, Account.Industry
FROM Contact
WHERE Account.Industry IN :industries
AND Account.Name LIKE :namePrefix
ORDER BY Account.Name, LastName
LIMIT 50
];
for (Contact c : contacts) {
System.debug(c.Account.Name + ' / ' + c.LastName);
}Reading c.Account.Name is safe here because the WHERE clause removes Contacts whose Account has no matching industry. A Contact without an Account cannot satisfy Account.Industry IN :industries. Don't rely on that for filters that can match nulls, which the next section covers.
What happens when the parent is empty
A lookup field can be empty. A Contact may have no Account. A relationship query behaves like a left outer join. The Contact is still a candidate row, and every parent field on that Contact reads as null.
This has direct effects on filters:
| Filter | Contact with Account (Industry = Technology) | Contact with no Account |
|---|---|---|
| `Account.Industry = 'Technology'` | Matches | Does not match |
| `Account.Industry != 'Technology'` | Does not match | Matches, because `null` is not `'Technology'` |
| `Account.Industry = null` | Does not match | Matches |
| `Account.Industry != null` | Matches | Does not match |
The second row catches many people. A "not equal" filter on a parent field returns children that have no parent at all. If you want only Contacts that have an Account and a different industry, say so explicitly:
SELECT Id, LastName, Account.Name, Account.Industry
FROM Contact
WHERE AccountId != null
AND Account.Industry != 'Technology'Filtering on the lookup field itself (AccountId != null) is the clearest test for "has a parent". It also does not depend on any parent field being populated. An Account with a blank Industry would match Account.Industry = null, which is a different condition from having no Account.
Sorting on parent fields
ORDER BY accepts a relationship path, with ASC or DESC and an optional null placement:
SELECT Id, LastName, Account.Name, Account.Owner.Name
FROM Contact
WHERE AccountId != null
ORDER BY Account.Owner.Name ASC, Account.Name DESC NULLS LAST, LastNameKey behaviors:
- Sorting is ascending by default.
- Records with a null sort value come first in ascending order and last in descending order. Add
NULLS FIRSTorNULLS LASTto control it. Contacts with no Account all sort as null onAccount.Name. - Multiple sort keys work as in any query. The first key is primary, and later keys break ties. Mix child and parent fields as needed.
- Picklist fields sort by the order the values are defined in the picklist, not alphabetically.
ORDER BY Account.Industryfollows the setup order of the industry values. - Some field types cannot be sorted. Long text areas and multi-select picklists are examples. The same restriction applies to the parent field as to a field on the queried object.
Filtering and sorting inside subqueries
The same ideas apply in the other direction. In a parent-to-child subquery, the child rows can be filtered and sorted on their own fields. They can also be filtered on the child's other parents.
SELECT Id, Name,
(SELECT Id, LastName, Owner.Name
FROM Contacts
WHERE Owner.IsActive = true
ORDER BY Owner.Name, LastName
LIMIT 5)
FROM Account
WHERE Industry = 'Technology'Here Owner.Name and Owner.IsActive are parent fields of each Contact, used inside the subquery. The LIMIT 5 applies per Account. The filter in the outer WHERE applies to Accounts only. It does not remove Contacts, and it does not filter on child fields. To filter the outer Accounts by what their Contacts look like, use a semi-join, which a later chapter covers.
Limits that affect parent-field queries
- Relationship depth. A path can go up to five levels from the queried object, for example
Contact.Account.Owner.Manager.Name. In practice, use the shortest path that works. - Filterable and sortable fields. Each field in a path must be accessible to the running user. Field-level security can make a query fail or hide values, depending on how the query runs.
- Query shape. Parent-field conditions in
WHEREdo not add extra queries in Apex. One SOQL statement counts as one query regardless of how many parents it traverses. They can still affect performance on large objects, because a filter on a parent field may not use an index on the child object. For large data volumes, prefer filters on indexed fields such asAccountId, then narrow further with parent fields. - Formula and polymorphic fields. Some parent fields, such as certain formula fields, cannot be used in filters. Polymorphic relationships such as
Owner,What, andWhohave narrower rules. A later chapter coversTYPEOFfor those.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `No such relationship 'Project__c'` | Used the field name instead of the relationship name | Use `Project__r` |
| Fewer rows than expected | Filter on a parent field excludes Contacts with no parent | Test `AccountId = null` separately |
| Extra rows with no parent | `!=` or `NOT` on a parent field matches nulls | Add `AccountId != null` |
| `System.NullPointerException` in Apex | Read `c.Account.Name` when `Account` is null | Use `c.Account?.Name` or filter nulls out |
| Unexpected sort order | Picklist order, or null parents sorting first | Use `NULLS LAST`, or sort on another field |
Exercise
Write a SOQL query that returns Contact Id and LastName, plus the parent Account Name, for Contacts whose Account is not in the 'Technology' industry. Exclude Contacts that have no Account. Sort by Account Name descending with nulls last, then by LastName. Explain why AccountId != null is needed.
Show answer
SELECT Id, LastName, Account.Name FROM Contact WHERE AccountId != null AND Account.Industry != 'Technology' ORDER BY Account.Name DESC NULLS LAST, LastName. Without AccountId != null, the condition Account.Industry != 'Technology' is also true for Contacts that have no Account, because their parent fields read as null. Those rows would be returned, and Apex code that reads c.Account.Name on them would throw a null-reference error.
Exercise
A custom object Task_c has a lookup field Projectc to Projectc. Write a query for Taskc rows whose parent project has Statusc equal to 'Active', sorted by the project name. Which name goes before the dot, `Projectc or Project_r`?
Show answer
SELECT Id, Name, Project_r.Name FROM Taskc WHERE Projectr.Statusc = 'Active' ORDER BY Projectr.Name. The relationship name `Projectr goes before the dot. Project_c` is the lookup field, which holds the parent's ID.