Salesforce Apex : Data Rollback

It is very often that we would want to insert 2 different lists of records into Salesforce with 2 DML insert statements as shown below:

 

try {
  insert list1;
  insert list2;
  ...
} catch (Exception e) {
  ...
}
This is still alright if there is any error occurs in the first DML insert statement as the error will be caught and the second DML insert statement won’t be execute. But, what if there is a problem occurs on the second DML insert statement? This will cause some bad data in your Salesforce if the data in the “list1” shouldn’t be inserted if there is any error occurs on “list2”.
To overcome this issue, you can implement transaction control into your code as follows:
Savepoint sp = Database.setSavepoint();

try {
  insert list1;
  insert list2;
  ...
} catch (Exception e) {
  ...
  Database.rollback(sp);
}

 

By doing this, Salesforce will help you to revert data back to the state before the first DML insert statement is executed.