# Accounts With More Than Five Contacts

**Type:** SOQL · **Difficulty:** Hard · **Topics:** GROUP BY, HAVING, COUNT

Practice this problem interactively (write and run your SOQL against realistic data): https://www.forcechallenges.com/problems/accounts-with-more-than-five-contacts

## Problem

**Scenario**
An account-management team wants to find its most heavily-staffed customers: the Accounts with the largest number of known contacts. These Accounts need a dedicated relationship owner, but only Accounts above a minimum size are worth the extra attention.

**Task**
Write one SOQL query on `Contact` that:
1. Ignores Contacts that are not linked to an Account (`AccountId` is null).
2. Groups the remaining Contacts by `AccountId`.
3. Keeps only Accounts that have **more than 5 Contacts**. An Account with exactly 5 is not included.
4. Sorts by the number of Contacts, **highest first**. Break ties by `AccountId` ascending.

**Expected output**
One row per qualifying Account with two columns: `AccountId` and `total` (the number of Contacts on that Account).

**Example**
Account A has 8 Contacts, Account B has 6, Account C has exactly 5, Account D has 2, and 3 Contacts have no Account.

| AccountId | total |
|---|---:|
| A | 8 |
| B | 6 |

Account C is excluded because 5 is not more than 5, Account D is too small, and the Contacts without an Account are ignored.

## Constraints

Use one aggregate query on Contact. Exclude Contacts that have no Account, group by AccountId, and keep groups with more than 5 Contacts using HAVING. Alias the count as `total`. Order by `total` descending, then AccountId ascending.

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