Delete records by a List of ids

Given a List of Ids that need to be deleted, can they be deleted without creating or querying the sObjects?

In my particular case I want to delete any records with ID’s still in a Maps keyset.

Map<Id, Account> accountIdToExistingAccountsMap = new Map<Id, Account>();
accountIdToExistingAccountsMap = new Map<Id, Account>([Select Id from Account]);
// Intermediate processing over accountIdToExistingAccountsMap.
// Entries to keep are removed from the Map

// TODO: Delete any accounts based on the Id's still in the maps keyset

The above example isn’t ideal, as you could just use the actual Account sObjects values from the Map. Consider it a simplified example to make the sample apex easier.

Answer

We can use the Database.delete(recordIDs, allOrNone) method to delete directly from the IDs.

List<Id> toDeleteIds = new List<Id>(accountIdToExistingAccountsMap.keySet());
Database.DeleteResult[] deleteResults = Database.delete(toDeleteIds, true);
for(Database.DeleteResult dr : deleteResults) {                   
    if (!dr.isSuccess()) {
        for(Database.Error err : dr.getErrors()) {
            System.debug(LoggingLevel.Error, 'The following error has occurred.'
                + '\n' + err.getStatusCode() + ': ' + err.getMessage()
                + '\n fields that affected this error: ' + err.getFields());
            // Plus further error handling as required
        }
    }
}

Attribution
Source : Link , Question Author : Daniel Ballinger , Answer Author : Daniel Ballinger

Leave a Comment