Intermediate 25 min read

Transactions and Savepoints

By the end of this lesson, you'll be able to:

  • Explain what a transaction is in the context of Apex execution
  • Use Database.setSavepoint() and Database.rollback() to undo changes mid-transaction
  • Recognize when a manual rollback is needed versus relying on all-or-nothing DML

Prerequisites: "The Database Class and Partial Success"

What a transaction is

Every time a trigger fires, a button is clicked, or (in this course's examples) a block of Execute Anonymous code runs, Apex treats that entire unit of work as one transaction. If an unhandled exception occurs anywhere inside it, every DML statement that already ran in that same transaction is automatically rolled back — nothing partial gets left behind from an outright crash.

Marking a point with a savepoint

Savepoint sp = Database.setSavepoint();

Account acc = new Account(Name = 'Riverbend Farms');
insert acc;

Contact con = new Contact(LastName = 'INVALID DATA THAT WILL FAIL LATER');
// ... later logic determines this whole operation should be undone

Database.rollback(sp);

Database.setSavepoint() marks a specific point in the transaction. Database.rollback(sp) undoes everything that happened after that point — including the insert acc above — as if it never ran, even though no exception was thrown.

A real business example: Multi-Step Order Processing

Savepoint sp = Database.setSavepoint();

try {
    Order__c order = new Order__c(Status__c = 'Processing');
    insert order;

    Payment__c payment = new Payment__c(Order__c = order.Id, Amount__c = -50); // invalid amount
    insert payment; // this throws

} catch (DmlException e) {
    Database.rollback(sp);
    System.debug('Order processing failed, all changes rolled back: ' + e.getMessage());
}

If creating the Payment__c fails partway through a multi-step process, rolling back to the savepoint undoes the already-inserted Order__c too — keeping the two genuinely in sync rather than leaving an orphaned order with no valid payment.

Exercise

Set a savepoint, insert an Account, then roll back to the savepoint and debug a message confirming the rollback happened.

Show hint

Database.setSavepoint(); ... Database.rollback(sp);

APEX

Transactions and Savepoints Quiz

1. What does Database.rollback(sp) do?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

A transaction is the full unit of work Apex executes as one atomic block — savepoints let you mark a point mid-transaction and roll every change back to it if something later goes wrong.