# Write a trigger to prevent Account deletion if it has one or more related Contacts.

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

Read it on the site: https://www.forcechallenges.com/interview-questions/write-a-trigger-to-prevent-account-deletion-if-it-has-one-or-more-related-contacts

## Answer

Use `before delete` and check for child Contacts with a subquery.

```apex
trigger AccountTrigger on Account (before delete) {
    for (Account a : [SELECT Id, (SELECT Id FROM Contacts LIMIT 1)
                      FROM Account WHERE Id IN :Trigger.oldMap.keySet()]) {
        if (!a.Contacts.isEmpty()) {
            Trigger.oldMap.get(a.Id).addError('Cannot delete an Account that has Contacts.');
        }
    }
}
```
Use `Trigger.old` records for `addError` in delete triggers. Note that a Contact-Account relationship with a master-detail or restricted delete would behave differently.

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