I have a apex class which will update some account field and contact field if some change occurs in opportunity. I am calling instance of this class inside trigger written on opportunity object. I am using Database.Update statements. I would like to know if an error occurs while updating a contact field then no update should take place in account and contact objects. I can place the entire code in try-catch block but I am not sure of this scenario.I have a brief idea on database.savepoint but how it can used effectively in this case for an entire rollback I am not sure. I do not want a code or conceptually how this works for me is of important.

  • Is all of this happening within one method or a single method that calls other methods without any async operations? If so Set a save point at the beginning and then of there is an error (checking with Database.saveresult) you can rollback to the state when you set the savepoint
    – Eric
    Jan 31 '17 at 4:28
  • @eric,all this happening in a one method Jan 31 '17 at 4:35
  • Have you read up on Transaction Control?
    – Adrian Larson
    Jan 31 '17 at 4:56

Essentially it follows this pattern:


     System.Savepoint sp = Database.setSavepoint(); //Save Database State

     .....DO STUFF.....

     Database.[Save][Upsert]Result[] sr = database.[update][insert]([YOURRECORDLIST],false);

     for(Integer x=0;x<sr.size();x++){

          if(sr[x].isSucess() == false){
              //We have an error, do stuff and rollback
              break; //Just for illustration completeness



This does the following

  1. Set a savepoint
  2. Does stuff you want to
  3. Performs a DML with AllOrNothing false
  4. Check the success of each record
  5. If any record fails, rollback to the last savepoint which in this case was the start of your method

On the rollback the database will be as it was at the method entry point since that is where the savepoint was set.

Note Stuff within [] are the various options (i.e. [save][upsert] pick either Save or Upsert) and are not meant as literal values. the empty [] denotes a list


try/catch will work as well but you will be limited on what you can do as it is all or nothing. Maybe it will meet your needs but generally you would not want to use a try/catch when you can actually evaluate the errors and make a decision on what to do....

  • ,what if there are two different methods. one to update account and one to update contact, so will I have to use database.savepoint in each of the methods? Jan 31 '17 at 5:25
  • @KrishnaCasukhela - You said it was all in one method? It all depends on the transaction boundaries
    – Eric
    Jan 31 '17 at 5:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.