Tuesday, August 28, 2018

How to get the Failure Record Ids From Database.SaveResult[]

if You Need To check The Success Record Ids and Failure Record Ids.
If DML Operation is Success Will Get Record Id From Database By Using getId()  Method in Database.SaveResult Class.
If any DML Operation Fails while Processing The Record no way to Get the Failure Record Id in
Database.Error Class

To Get the Failure Record Id, We can use List index Property to get the Id of the failed record.

Check Bellow code
list<Account> lstAccToUpdate = new list<Account>();
list<Account> lstAccounts = [Select id, Name, Industry From Account limit 10];
for(Account aIterator : lstAccounts) {
    aIterator.Industry = 'Banking';
if(lstAccToUpdate != null && !lstAccToUpdate.isEmpty()) {
    Database.SaveResult[] result = Database.update(lstAccToUpdate,false);
    for(Integer i=0; i < result.size(); i++) {
        if(result.get(i).isSuccess()) {
            System.debug('Records are updated Successfully');
        else if(!result.get(i).isSuccess()) {
            Database.Error errors =  result.get(i).getErrors().get(0);
            System.debug('Error Occurs While Processing The Record'+errors.getMessage());
            System.debug('Failure Record Ids While Updating'+result.get(i).Id);

Let us know if you have any queries.
Happy Learning!!


  1. Hi, I think the code above doesn't work. The result list doesn't contain the Id for failed records. If you assume that the order of the results list matches the order of the records in the original list object (lstAccToUpdate) - then you can use indexing to infer the id of the record that failed to update.
    So this would mean change last line to:
    System.debug('Failure Record Ids While Updating'+lstAccToUpdate.get(i).Id);
    I don't know if you can rely on Salesforce maintaining the order - but I think this is what your suggested approach is.

    1. Failed records will not be stored in updated list so we can not get failed record id from that result . The above code is correct.