ApexSensei

Drills › Change records (DML)

Delete challenge-created records

Change records (DML) · Intermediate · 12 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A cleanup job must remove only the temporary rows it created during the current transaction.

Delete two tagged Accounts in one statement and prove they moved to the Recycle Bin.

What you will learn

delete removes records by Id. Delete only records your code created, and delete the whole list in one statement.

delete accounts;
Integer inBin = [
    SELECT COUNT() FROM Account
    WHERE Id IN :ids AND IsDeleted = true ALL ROWS
];

Deleted records go to the Recycle Bin. Normal queries skip them. ALL ROWS includes them.

Gotcha. Never pick records to delete with a broad query like LIMIT 1.

The task

Create two tagged Accounts, delete them in one statement, and prove they moved to the Recycle Bin.

Examples:

  • after insert, a count by their Ids → Created count: 2
  • after delete, the same count → Remaining active: 0 and Delete statements: 1
  • a count that adds IsDeleted = true ALL ROWS → In recycle bin: 2

Requirements:

  1. Insert the list once and add each new Id to createdIds.
  2. Count Accounts WHERE Id IN :createdIds before you delete.
  3. Delete the whole list in one statement, outside any loop. Read Limits.getDmlStatements() into dmlBefore just before it and again after it.
  4. Count again the normal way, then count with AND IsDeleted = true ALL ROWS.
  5. Print Created count:, Remaining active:, In recycle bin: and Delete statements: (after minus before).

Starter code

String tag = 'AS-DELETE-' + UserInfo.getUserId() + '-' +
    String.valueOf(Datetime.now().getTime());
List<Account> accounts = new List<Account>{
    new Account(Name = tag + '-A', Description = tag),
    new Account(Name = tag + '-B', Description = tag)
};

Set<Id> createdIds = new Set<Id>();
Integer dmlBefore;

When it passes

Both owned Accounts exist before one bulk delete. Afterwards a normal query finds none, and an ALL ROWS query finds both in the Recycle Bin.

Try this drill free

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

‹ Update a tagged Account · Bulk update once ›