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.

1 Answer 1


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
  • 3
    +1 It's about time someone noticed that you don't need real sObjects. ☺
    – sfdcfox
    Aug 10, 2017 at 2:14
  • 1
    Seemed like massive overkill to spool up all those sObjects on the heap just to turn around and delete them all. Aug 10, 2017 at 2:30
  • 1
    @DanielBallinger - In your case though you already have the sObject in the map Values right? So using the sObjects would be no different than the Ids right? Or does passing sObjects to the delete increase the heap more than passing the Ids?
    – Eric
    Aug 10, 2017 at 2:36
  • 1
    @Eric Yeah, my example was perhaps a bit simplistic and I could have just directly used the .values() from the map. My real world map is more complicated and the values aren't actually the sObjects I want to delete. Aug 10, 2017 at 2:42

You must log in to answer this question.

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