# Write a trigger on Contact to ensure a single Account cannot have more than one "Primary Contact" (Is_Primary__c = true).

**Topic:** Development · **Difficulty:** Medium · **Asked at:** Cognizant, Infosys, EY · **Tags:** apex-trigger, trigger, coding, scenario, validation

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-trigger-on-contact-to-ensure-a-single-account-cannot-have-more-than-one-primary-contact-is-primary-c

## Answer

Use `before insert, before update`. Count primaries within the incoming batch and against existing primaries in the database.

```apex
trigger ContactTrigger on Contact (before insert, before update) {
    Set<Id> accIds = new Set<Id>();
    for (Contact c : Trigger.new) if (c.Is_Primary__c && c.AccountId != null) accIds.add(c.AccountId);
    Set<Id> hasPrimary = new Set<Id>();
    for (Contact e : [SELECT AccountId FROM Contact WHERE AccountId IN :accIds
                      AND Is_Primary__c = true AND Id NOT IN :Trigger.new]) hasPrimary.add(e.AccountId);
    for (Contact c : Trigger.new) {
        if (c.Is_Primary__c && c.AccountId != null) {
            if (!hasPrimary.add(c.AccountId)) c.addError('Account already has a primary Contact.');
        }
    }
}
```
Adding to the set also catches duplicates inside the same batch.

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