# Write a SOQL query to fetch Accounts that have both related Contacts AND related Opportunities.

**Topic:** Development · **Difficulty:** Medium · **Asked at:** Deloitte, Accenture, Persistent · **Tags:** soql, scenario, semi-join

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-soql-query-to-fetch-accounts-that-have-both-related-contacts-and-related-opportunities

## Answer

Use two semi-joins combined with AND, one against Contact and one against Opportunity.

```soql
SELECT Id, Name FROM Account
WHERE Id IN (SELECT AccountId FROM Contact)
  AND Id IN (SELECT AccountId FROM Opportunity)
```
Both subqueries return Account Ids, so only Accounts present in both are returned.

---
Source: ForceChallenges · last updated 2026-10-19
