---
title: "SOQL Semi-Join"
url: "https://blog.beyondthecloud.dev/tips/soql-semi-join"
category: "SOQL"
published: "2024-01-02"
---

# SOQL Semi-Join

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

### SOQL Semi-Join

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.
