# Write a SOQL query to fetch Accounts that have more than 5 Contacts (SELECT AccountId, COUNT(Id) FROM Contact GROUP BY AccountId HAVING COUNT(Id) > 5).

**Topic:** Development · **Difficulty:** Medium · **Asked at:** Deloitte, Accenture, Wipro · **Tags:** soql, scenario, aggregate, having

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-soql-query-to-fetch-accounts-that-have-more-than-5-contacts-select-accountid-count-id-from-contact

## Answer

Group Contacts by AccountId and use `HAVING` to keep only groups with more than five Contacts.

```soql
SELECT AccountId, COUNT(Id) total FROM Contact
WHERE AccountId != null
GROUP BY AccountId
HAVING COUNT(Id) > 5
```
To return the Account details too, put this in a semi-join: `SELECT Id, Name FROM Account WHERE Id IN (...)` is not allowed with HAVING in the subquery, so query the Account Ids in Apex from the AggregateResult first.

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