# Roll Up Contact Count

**Type:** Apex trigger · **Difficulty:** Hard · **Object:** Contact · **Topics:** after insert, after delete, Aggregate SOQL, Roll-up

Practice this problem interactively (write and run your Apex trigger against realistic data): https://www.forcechallenges.com/problems/roll-up-contact-count

## Problem

Accounts have a custom field `Number_of_Contacts__c`. Keep it accurate with an **after insert** and **after delete** trigger on **Contact**.

For every Account touched by the DML, recompute the number of Contacts that reference it and update the Account.

This is the classic *roll-up summary on a lookup* interview question. It must survive bulk loads of 600 contacts spread across many accounts — **aggregate SOQL + one DML per chunk** is the expected pattern.

## Constraints

- Recompute with `SELECT AccountId, COUNT(Id) n FROM Contact WHERE AccountId IN :ids GROUP BY AccountId`.
- Accounts whose last contact is deleted must go back to 0.
- ≤ 1 SOQL and ≤ 1 DML per chunk.

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