# Write a trigger to prevent duplicate Contacts based on Email and Phone when inserting or updating a Contact.

**Topic:** Development · **Difficulty:** Medium · **Asked at:** Accenture, Deloitte, HCL · **Tags:** apex-trigger, trigger, coding, scenario, duplicates

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-trigger-to-prevent-duplicate-contacts-based-on-email-and-phone-when-inserting-or-updating-a-contact

## Answer

Use `before insert, before update`. Compare against existing Contacts in the database **and** within the same batch.

```apex
trigger ContactTrigger on Contact (before insert, before update) {
    Set<String> emails = new Set<String>(), phones = new Set<String>();
    for (Contact c : Trigger.new) {
        if (c.Email != null) emails.add(c.Email);
        if (c.Phone != null) phones.add(c.Phone);
    }
    Set<String> seen = new Set<String>();
    for (Contact e : [SELECT Id, Email, Phone FROM Contact
                      WHERE (Email IN :emails OR Phone IN :phones) AND Id NOT IN :Trigger.new]) {
        seen.add(e.Email + '|' + e.Phone);
    }
    for (Contact c : Trigger.new) {
        String key = c.Email + '|' + c.Phone;
        if (!seen.add(key)) c.addError('Duplicate Contact with same Email and Phone.');
    }
}
```
In production, prefer Duplicate/Matching Rules where possible.

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