# When a Lead is created with an Email that already exists on an existing Contact, block the Lead creation or automatically link/merge it.

**Topic:** Development · **Difficulty:** Medium · **Asked at:** Deloitte, ZS Associates, PwC · **Tags:** apex-trigger, trigger, coding, scenario, duplicates

Read it on the site: https://www.forcechallenges.com/interview-questions/when-a-lead-is-created-with-an-email-that-already-exists-on-an-existing-contact-block-the-lead-creation-or

## Answer

Use `before insert` on Lead, query Contacts with matching emails, and either block or link via a custom lookup (e.g. `Existing_Contact__c`).

```apex
trigger LeadTrigger on Lead (before insert) {
    Set<String> emails = new Set<String>();
    for (Lead l : Trigger.new) if (l.Email != null) emails.add(l.Email);
    Map<String, Contact> byEmail = new Map<String, Contact>();
    for (Contact c : [SELECT Id, Email FROM Contact WHERE Email IN :emails]) byEmail.put(c.Email, c);
    for (Lead l : Trigger.new) {
        if (l.Email != null && byEmail.containsKey(l.Email)) {
            // Option A: block
            l.addError('A Contact with this email already exists.');
            // Option B: l.Existing_Contact__c = byEmail.get(l.Email).Id;
        }
    }
}
```
Standard Duplicate Rules and Matching Rules can do this across Lead/Contact without code.

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