Sub topic 3
Filtering Parents by Their Children in SOQL
Assume you know SELECT, FROM, WHERE, LIMIT, relationship names, and basic Salesforce object relationships.
Semi-joins and Anti-joins
A semi-join filters parent records by matching child records. Use IN with a subquery. An anti-join uses NOT IN to find parents without matching children.
SELECT Id, Name
FROM Account
WHERE Id IN (
SELECT AccountId
FROM Contact
WHERE Email != null
)This returns accounts with at least one contact that has an email address.
SELECT Id, Name
FROM Account
WHERE Id NOT IN (
SELECT AccountId
FROM Opportunity
)This returns accounts with no opportunities.
| Query | Meaning |
|---|---|
| `Id IN (SELECT AccountId FROM Contact ...)` | Parent has a matching child |
| `Id NOT IN (SELECT AccountId FROM Opportunity)` | Parent has no matching child |
Polymorphic Relationships and `TYPEOF`
A polymorphic relationship can point to different object types. For example, an Event record's What field can refer to an Account or an Opportunity. TYPEOF selects fields based on the actual type.
SELECT Id, Subject,
TYPEOF What
WHEN Account THEN Name, Phone
WHEN Opportunity THEN Name, Amount
END
FROM EventAggregating Across Relationships
Use an aggregate function such as COUNT with GROUP BY to summarize related records.
SELECT Account.Name, COUNT(Id)
FROM Contact
GROUP BY Account.NameThis counts contacts for each account. Contacts without an account form a group with a null parent value.
Combining Both Directions
One query can select parent fields and also include child records. A child subquery can traverse back to its parent.
SELECT Id, Name, Owner.Name,
(SELECT Id, LastName, Account.Owner.Name
FROM Contacts
ORDER BY LastName
LIMIT 5)
FROM Account
WHERE Industry = 'Technology'Limits and Common Mistakes
- Use the child relationship name, such as
ContactsorTasks__r, in a subquery. - Use
Project__r, notProject__c, when traversing from a custom child to its parent. - Do not put
ORDER BYorLIMITinside a semi-join. - Check for null lookup parents before dereferencing them in Apex.
- Remember that relationship and aggregate queries still count against Salesforce query and row limits.
Exercise
Which query finds accounts that have at least one contact with an email address?
Show answer
SELECT Id FROM Account WHERE Id IN (SELECT AccountId FROM Contact WHERE Email != null)