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:
AccountId is null).AccountId.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.
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.
2 row(s), order checked
| # | total | AccountId |
|---|---|---|
| 1 | 8 | 001000000000001AAA |
| 2 | 6 | 001000000000002AAA |