trigger preventAccountDeletionifopp on Account (before delete) {
    for(account accdel:trigger.old){
       Opportunity oppprevent =[select Name,(select Name,Owner from Opportunitys)from ACCOUNT =: accdel.id ];
        if(oppprevent.size() > 0){
          accdel.adderror('Opportunity record is refering this record.So, you cannot delete it...!');

1 Answer 1


Generally speaking, you can just use a set of Id values, gathered from an AggregateResult query:

Set<Id> accountIds = new Map<Id, AggregateResult>(
    [SELECT AccountId Id 
     FROM Opportunity 
     WHERE AccountId = :Trigger.old
     GROUP BY AccountId]).keySet();
for(Account record: Trigger.old) {
    if(accountIds.contains(record.Id)) {
        record.addError('Please delete all opportunities before deleting the account.');

This is a classic example of bulkification. You can read more about that here.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .