Database.SaveResult - how to get the Id of the record where Update failed?

We can use List index Property to get the Id of the failed record .The Index of the List which we are updating and also the result set retrieved has the same index .Using the above property for our advantage we can draft a pseduo code as below

List<Database.SaveResult> updateResults = Database.upsert(arudate, false);
for(Integer i=0;i<updateResults.size();i++){
    if (updateResults.get(i).isSuccess()){
        updateResults.get(i).getId();

    }else if (!updateResults.get(i).isSuccess()){
        // DML operation failed
        Database.Error error = updateResults.get(i).getErrors().get(0);
        String failedDML = error.getMessage();
        arudate.get(i);//failed record from the list
        system.debug('Failed ID'+arudate.get(i).Id);
     }

}

Use an integer as a counter and get the relevant record from the list.

Database.SaveResult[] srList = Database.update(updlist,false);
    Integer i=0;
    for (Database.SaveResult sr : srList) {
        if (!sr.isSuccess()) {
            for(Database.Error err : sr.getErrors()) { 
                System.debug(updlist.get(i).Id + ': ' + err.getMessage());
            }
        }
        i++;
    }  
}

Tags:

Dml

Apex