What is Database.setSavepoint in Salesforce?

Database.setSavepoint() is used to define a point at which DML operations can be rolled back. If any error occurs during DML Operations, that contains many statements, the application will be rolled back to the most recent save point and the entire transaction will not be aborted.


Savepoint sp = Database.setSavepoint();;

Account a = new Account();

a.AccountNumber = '2';
insert a;

Contact c = new Contact(Account = a.Id);
insert c;
catch(Exception e)

In this example, if any error occurs while inserting the Contact 'c', then the entire transaction will be rolled back to savepoint sp ( as specified in the catch section by Database.rollback method).

Note the following:
  • If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, the later savepoint variables become invalid. For example, if you generated savepoint SP1 first, savepoint SP2 after that, and then you rolled back to SP1, the variable SP2 would no longer be valid. You will receive a runtime error if you try to use it.
  • References to savepoints cannot cross trigger invocations, because each trigger invocation is a new execution context. If you declare a savepoint as a static variable then try to use it across trigger contexts you will receive a runtime error.
  • Each savepoint you set counts against the governor limit for DML statements.


  1. what do we mean by this point : " References to savepoints cannot cross trigger invocations, ."

    1. Its not like that. All operations will be rolled back starting from SavePoint.

      Thank You!


Sharing is Caring!!! Share this with your friends!!!

submit to reddit