# Maintain Account Contact and Opportunity Counts

**Type:** Apex trigger · **Difficulty:** Hard · **Object:** Contact · **Topics:** Apex Trigger, Bulkification, Aggregate SOQL, Contact, Opportunity, Roll-up

Practice this problem interactively (write and run your Apex trigger against realistic data): https://www.forcechallenges.com/problems/maintain-account-contact-opportunity-counts

## Problem

Write bulk-safe Apex triggers to maintain two custom count fields on Account: `Contact_Count__c` and `Opportunity_Count__c`. The Contact trigger must recalculate the Contact count after insert, update, delete, and undelete. The Opportunity trigger must recalculate the Opportunity count after insert, update, delete, and undelete. Handle records reassigned to another Account and reset counts to zero when the last child is removed. Use aggregate SOQL and avoid queries or DML inside loops.

## Constraints

- Create `Contact_Count__c` and `Opportunity_Count__c` as Number fields on Account.
- Recalculate counts for all affected Account IDs, including both old and new Account IDs on update.
- Use bulk-safe logic and aggregate queries.
- The platform trigger runner validates the Contact-trigger path; include the corresponding Opportunity-trigger implementation in your submission.

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