Savepoint and rollback
Change records (DML) · 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 account;
Database.rollback(checkpoint);
Unlike delete, a rollback leaves nothing in the Recycle Bin. ALL ROWS finds no row.
Gotcha. Rollback does not clear account.Id, so insert account again fails. Insert a new Account, or account.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 withALL ROWS→After rollback: 0andEven in recycle bin: 0 account.Idafter the rollback →Id still set: true
Requirements:
- Keep the starter's savepoint, which is set before any DML.
- Insert the Account, save its Id, and count Accounts with that Id.
- Roll back to the savepoint, count with the same Id again, then count once more with
ALL ROWS. - Print
Before rollback:,After rollback:,Even in recycle bin:andId still set:(isaccount.Idstill not null?).
Starter code
String tag = 'AS-ROLLBACK-' + UserInfo.getUserId() + '-' +
String.valueOf(Datetime.now().getTime());
Savepoint checkpoint = Database.setSavepoint();
Account account = 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 account.Id is still set.
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 ›