# Write a SOQL query to count the number of Contacts associated with each Account (SELECT AccountId, COUNT(Id) FROM Contact GROUP BY AccountId).

**Topic:** Development · **Difficulty:** Easy · **Asked at:** TCS, Infosys, Cognizant · **Tags:** soql, scenario, aggregate, group-by

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-soql-query-to-count-the-number-of-contacts-associated-with-each-account-select-accountid-count-id

## Answer

Aggregate Contacts grouped by AccountId.

```soql
SELECT AccountId, COUNT(Id) total FROM Contact
WHERE AccountId != null
GROUP BY AccountId
```
In Apex: `(Id) ar.get('AccountId')` and `(Integer) ar.get('total')`.

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