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: 0andDelete statements: 1 - a count that adds
IsDeleted = true ALL ROWS→In recycle bin: 2
Requirements:
- Insert the list once and add each new Id to
createdIds. - Count Accounts
WHERE Id IN :createdIdsbefore you delete. - Delete the whole list in one statement, outside any loop. Read
Limits.getDmlStatements()intodmlBeforejust before it and again after it. - Count again the normal way, then count with
AND IsDeleted = true ALL ROWS. - Print
Created count:,Remaining active:,In recycle bin:andDelete 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.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.