Delete and Undelete
By the end of this lesson, you'll be able to:
- Delete one or more records with delete
- Explain what the Recycle Bin is and how undelete restores a record
- Recognize that delete requires an existing Id, like update
Prerequisites: "Upsert and External IDs"
Deleting a record
Account acc = [SELECT Id FROM Account WHERE Name = 'Northwind Traders' LIMIT 1];
delete acc;
Just like update, delete needs an existing Id to identify which row to remove — you can't delete a record that was never inserted or queried, for the same reason update can't modify one.
It's not gone immediately: the Recycle Bin
Account acc = [SELECT Id FROM Account WHERE Name = 'Northwind Traders' LIMIT 1];
delete acc;
undelete acc;
System.debug('Restored: ' + acc.Name);
A deleted record moves to Salesforce's Recycle Bin rather than being permanently destroyed right away — undelete (using the same Id) restores it, exactly reversing the delete. This is a real safety net against an accidental mass deletion.
Deleting a List at once
List<Account> staleAccounts = [SELECT Id FROM Account WHERE LastActivityDate < :Date.today().addYears(-2)];
delete staleAccounts;
Exactly like insert and update, delete accepts a List for a single bulk operation — one DML statement removing every matching record, never a delete call inside a loop.
Exercise
Given Account acc already queried with Id, delete it and then undelete it, debugging a message after each step.
Show hint
delete acc; then undelete acc;
Delete and Undelete Quiz
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
delete removes a record — but not permanently at first, since Salesforce moves it to the Recycle Bin, where undelete can bring it back.