List<Contact> conList = [SELECT Id, Email FROM Contact WHERE LastName='Smith'];

List<Contact> listToUpdate = new List<Contact>(); for(Contact con:conList) { if(con.Email != null) continue;

else listToUpdate.add(con);

delete listToUpdate; }

it should delete records with no email.error: System.DmlException: Delete failed. First exception on row 0 with id 0035j00000LnS5fAAF; first error: ENTITY_IS_DELETED, entity is deleted: []

1

There are 1 best solutions below

0
eyescream On BEST ANSWER

The way you format the code is rubbish. You don't see that you have put the delete operation inside the loop. If you have many contacts and you call delete on something that was deleted in previous iteration - yes, that's the error you'll get.

This is better:

List<Contact> conList = [SELECT Id, Email FROM Contact WHERE LastName='Smith'];

List<Contact> listToUpdate = new List<Contact>(); 
for(Contact con:conList) {
    if(con.Email != null){
        continue;
    } else {
        listToUpdate.add(con);
    }
}
delete listToUpdate; 

this is best

delete [SELECT Id
    FROM Contact
    WHERE LastName='Smith' AND Email = null];

because it'll query the minimum amount of rows and there's no loop at all.