Sub topic 9
Filtering parents by their children: semi-joins and anti-joins
This chapter assumes you can write basic SOQL (SELECT, FROM, WHERE, ORDER BY, LIMIT). It also assumes you know the difference between lookup and master-detail fields, and that you have seen child-to-parent dot notation and parent-to-child subqueries in the SELECT list. Apex snippets use plain loops and collections.
The problem: a subquery in SELECT does not filter
A parent-to-child subquery in the SELECT list returns children, but it never removes parents. Consider this query:
SELECT Id, Name,
(SELECT Id FROM Contacts WHERE Email != null)
FROM AccountIt returns every account. Accounts with no matching contacts come back with an empty Contacts list. If you want only the accounts that have at least one contact with an email address, the filter belongs in the WHERE clause of the outer query.
SOQL has two forms for this:
- A semi-join keeps the parents that have at least one matching child. It uses
INwith a subquery. - An anti-join keeps the parents that have no matching child. It uses
NOT INwith a subquery.
Both compare an ID field on the outer object with a set of IDs produced by an inner query.
Semi-joins with IN
This semi-join returns only the accounts that have at least one contact with an email address:
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact WHERE Email != null)The query runs in two logical steps:
- The inner query finds every contact with an email and collects its
AccountId. - The outer query returns the accounts whose
Idis in that collection.
The inner query's own WHERE clause decides what counts as a matching child. Here the condition is "has an email". It could just as well be "has a closed-won opportunity" or "has an open case with high priority".
The diagram above is replaced by the one below, which shows the flow.
Which field the subquery selects
The subquery must select exactly one field, and that field must be an ID type. It is usually a lookup or master-detail field on the child, such as AccountId, or the child's own Id. The outer field is also an ID or reference field, and the two sides should point at the same kind of record.
The semi-join does not have to go from parent to child. You can also filter children by a condition on their parent without dot notation:
SELECT Id, LastName
FROM Contact
WHERE AccountId IN (SELECT Id FROM Account WHERE Industry = 'Technology')This gives the same rows as WHERE Account.Industry = 'Technology'. The dot-notation form is usually shorter. The semi-join form is useful when the inner query needs a different object than the relationship allows, for example WHERE Id IN (SELECT ContactId FROM CampaignMember WHERE Status = 'Responded').
Anti-joins with NOT IN
An anti-join reverses the test. This query returns accounts that have no opportunities:
SELECT Id, Name
FROM Account
WHERE Id NOT IN (SELECT AccountId FROM Opportunity)The typical uses are finding gaps in your data:
- Accounts with no contacts:
WHERE Id NOT IN (SELECT AccountId FROM Contact) - Accounts with no open cases:
WHERE Id NOT IN (SELECT AccountId FROM Case WHERE IsClosed = false) - Projects with no tasks:
WHERE Id NOT IN (SELECT Project__c FROM Task__c)
The last one uses the custom objects from earlier in this tutorial. The subquery selects the lookup field name Project__c, not the relationship name Project__r.
Reading the second example carefully
NOT IN (SELECT AccountId FROM Case WHERE IsClosed = false) returns accounts with no open cases. It does not return accounts that have only closed cases and nothing else in a separate sense. An account with closed cases and no open ones qualifies, as does an account with no cases at all. If you want "has cases, but none open", you have to combine an IN and a NOT IN (see below).
Combining several joins
You can use more than one semi-join or anti-join in one WHERE clause, joined with AND. This finds accounts that have contacts but no opportunities:
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact)
AND Id NOT IN (SELECT AccountId FROM Opportunity)You can also mix them with ordinary conditions:
SELECT Id, Name, Industry
FROM Account
WHERE Industry = 'Technology'
AND Id IN (SELECT AccountId FROM Contact WHERE Email != null)
ORDER BY Name
LIMIT 50ORDER BY and LIMIT belong to the outer query only.
Restrictions to remember
Semi-joins and anti-joins are stricter than a general SQL subquery. Check the SOQL reference for your API version, because details change. These rules are the ones you will hit most often:
| Rule | What it means |
|---|---|
| One selected field | The subquery selects a single ID or reference field. It cannot select a field through a relationship, such as `Account.Id`. |
| Only in WHERE | The `IN`/`NOT IN` subquery goes in the outer `WHERE` clause. It cannot sit in the `SELECT` list as a filter. |
| No OR with the subquery | You cannot combine a semi-join or anti-join with `OR` at the same level. Use `AND`, or run two queries. |
| No nesting of joins | A semi-join or anti-join subquery cannot contain another semi-join or anti-join. |
| No ORDER BY or LIMIT inside | The inner query is a filter set, not a ranked list, so these clauses are not allowed there. |
An inner query that reads a very large child object can also hit limits on query time or rows scanned. Keep the inner WHERE selective, and filter on indexed fields where you can.
Using semi-joins in Apex
You can run these queries inline in Apex without any extra setup:
List<Account> noOpps = [
SELECT Id, Name
FROM Account
WHERE Id NOT IN (SELECT AccountId FROM Opportunity)
LIMIT 200
];
System.debug(noOpps.size() + ' accounts have no opportunities');The inner query runs on the server as part of the same statement. It does not count as a separate query against your Apex governor limit for the number of SOQL queries, which is one benefit over doing the work in code.
The alternative is to collect IDs in Apex and bind them:
Set<Id> accountIds = new Set<Id>();
for (Contact c : [SELECT AccountId FROM Contact WHERE Email != null AND AccountId != null LIMIT 10000]) {
accountIds.add(c.AccountId);
}
List<Account> withEmailContacts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
System.debug(withEmailContacts.size());This does the same job in two statements. It is more flexible, because you can change the ID set in code before the second query. It also costs two SOQL queries and holds the IDs in heap memory, and the LIMIT quietly drops matches beyond the cap. Prefer the single-query semi-join when you do not need to touch the IDs.
Semi-join, dot notation, or subquery in SELECT?
| You want | Use |
|---|---|
| Child rows, filtered by a parent field | Dot notation: `WHERE Account.Industry = 'Technology'` |
| Parent rows, with their children attached | Subquery in `SELECT`: `(SELECT Id FROM Contacts)` |
| Only parents that have (or lack) matching children | Semi-join or anti-join in `WHERE` |
| Parents that have children, with those children attached | Both: a semi-join in `WHERE` and a subquery in `SELECT` |
The last row is a common pattern:
SELECT Id, Name,
(SELECT Id, LastName FROM Contacts WHERE Email != null)
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact WHERE Email != null)The inner conditions repeat on purpose. The WHERE subquery decides which accounts come back. The SELECT subquery decides which contacts are attached to them. Without the repeat, the contact list could include rows you meant to exclude, or the accounts could include ones with no matching contacts.
Common mistakes
- Expecting a SELECT subquery to remove parents. It never does. Use
INorNOT IN. - Selecting a relationship path in the subquery.
SELECT Account.Id FROM Contactis invalid. SelectAccountId. - Using the relationship name as the object. The subquery's
FROMtakes an object name such asContactorTask__c. - Reading
NOT INas "has no children of any kind". It means "has no children that satisfy the innerWHERE". - Adding OR.
WHERE Industry = 'Technology' OR Id IN (...)is rejected. Run two queries and merge the results in Apex. - Adding ORDER BY or LIMIT inside. Put them on the outer query.
Exercise
Write one SOQL query that returns the Id and Name of every Account that has at least one Opportunity with StageName = 'Closed Won' and has no Case with IsClosed = false. Then say whether you could add "OR Industry = 'Technology'" to the same WHERE clause.
Show answer
SELECT Id, Name FROM Account WHERE Id IN (SELECT AccountId FROM Opportunity WHERE StageName = 'Closed Won') AND Id NOT IN (SELECT AccountId FROM Case WHERE IsClosed = false). No. A semi-join or anti-join cannot be combined with OR at the same level, so you would run a second query for Industry = 'Technology' and merge the two result lists in Apex.
Exercise
A developer writes SELECT Id, Name, (SELECT Id FROM Contacts) FROM Account and expects only accounts that have contacts. What do they get, and how do they fix the query so that accounts without contacts are excluded?
Show answer
They get every account, and accounts without contacts have an empty Contacts list. Add a semi-join: SELECT Id, Name, (SELECT Id FROM Contacts) FROM Account WHERE Id IN (SELECT AccountId FROM Contact).