SOQL Semi-Join

Consideration: Semi-joins do NOT count against the query limit. Semi-joins COUNT against the aggregated query limit.

Have you ever tried to retrieve parent records based on a child's condition?

Probably you did something like this:

You can accomplish this more easily using a Semi-Join:

apex
List<Opportunity> opportunities = [
    SELECT Id, AccountId
    FROM Opportunity
    WHERE StageName = 'Closed Lost'
];

Set<Id> accountIds = new Set<Id>();

for (Opportunity opp : opportunities) {
    accountIds.add(opp.AccountId);
}

List<Account> accounts = [
    SELECT Id, Name
    FROM Account
    WHERE Id IN :accountIds
];
sql
SELECT Id, Name
FROM Account
WHERE Id IN (
    SELECT AccountId
    FROM Opportunity
    WHERE StageName = 'Closed Lost'
)

Consideration: Semi-joins do NOT count against the query limit. Semi-joins COUNT against the aggregated query limit.

Text and code were extracted from the original slide. Plain-text version of the whole catalog