ApexSensei

Drills › DML operations

Savepoint and rollback

DML operations · Intermediate · 15 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A multi-step operation must be able to abandon temporary database work when a later step cannot continue.

Insert a tagged Account after a savepoint, roll back, and show the row is gone while the Id stays on the variable.

What you will learn

A savepoint marks a spot in the current transaction. Database.rollback undoes every insert, update and delete made after that spot.

Savepoint checkpoint = Database.setSavepoint();
insert acct;
Database.rollback(checkpoint);

Unlike delete, a rollback leaves nothing in the Recycle Bin. ALL ROWS finds no row.

Gotcha. Rollback does not clear acct.Id, so insert acct again fails. Insert a new Account, or acct.clone(false), instead.

The task

Insert a tagged Account after a savepoint, roll back, and show that the row is gone but the Id is still on the variable.

Examples:

  • a count by the new Id before rollback → Before rollback: 1
  • the same count after Database.rollback, then with ALL ROWS → After rollback: 0 and Even in recycle bin: 0
  • acct.Id after the rollback → Id still set: true

Requirements:

  1. Keep the starter's savepoint, which is set before any DML.
  2. Insert the Account, save its Id, and count Accounts with that Id.
  3. Roll back to the savepoint, count with the same Id again, then count once more with ALL ROWS.
  4. Print Before rollback:, After rollback:, Even in recycle bin: and Id still set: (is acct.Id still not null?).

Starter code

String tag = 'AS-ROLLBACK-' + UserInfo.getUserId() + '-' +
    String.valueOf(Datetime.now().getTime());
Savepoint checkpoint = Database.setSavepoint();
Account acct = new Account(Name = tag, Description = tag);

Id attemptedId;

When it passes

The tagged Account exists after the insert, the same Id finds zero rows after the rollback, and acct.Id is still set.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Handle Database.SaveResult · Insert an Account with Contacts ›