# When a new Contact is inserted without an AccountId, check if an Account exists whose Domain__c matches the Contact's email domain (e.g., @acme.com). If found, link it; if not, create a new Account and link the Contact.

**Topic:** Development · **Difficulty:** Hard · **Asked at:** Salesforce, Deloitte, Persistent, Nagarro · **Tags:** apex-trigger, trigger, coding, scenario

Read it on the site: https://www.forcechallenges.com/interview-questions/when-a-new-contact-is-inserted-without-an-accountid-check-if-an-account-exists-whose-domain-c-matches-the

## Answer

Use `before insert` on Contact. Extract the email domain, match Account `Domain__c`, and create missing Accounts in bulk.

```apex
trigger ContactTrigger on Contact (before insert) {
    Map<String, List<Contact>> byDomain = new Map<String, List<Contact>>();
    for (Contact c : Trigger.new) {
        if (c.AccountId == null && c.Email != null && c.Email.contains('@')) {
            String d = c.Email.substringAfter('@').toLowerCase();
            if (!byDomain.containsKey(d)) byDomain.put(d, new List<Contact>());
            byDomain.get(d).add(c);
        }
    }
    Map<String, Account> accByDomain = new Map<String, Account>();
    for (Account a : [SELECT Id, Domain__c FROM Account WHERE Domain__c IN :byDomain.keySet()]) accByDomain.put(a.Domain__c.toLowerCase(), a);
    List<Account> newAccs = new List<Account>();
    for (String d : byDomain.keySet()) if (!accByDomain.containsKey(d)) {
        Account a = new Account(Name = d, Domain__c = d); accByDomain.put(d, a); newAccs.add(a);
    }
    insert newAccs;
    for (String d : byDomain.keySet()) for (Contact c : byDomain.get(d)) c.AccountId = accByDomain.get(d).Id;
}
```

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