Intermediate
20 min read
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;
Account acc = [SELECT Id FROM Account WHERE Name = 'Northwind Traders' LIMIT 1];— queries the record, including itsId.delete acc;— just likeupdate,deleteneeds an existingIdto identify which row to remove — you can't delete a record that was never inserted or queried.
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);
Account acc = [SELECT Id FROM Account WHERE Name = 'Northwind Traders' LIMIT 1];— queries the record.delete acc;— moves it to Salesforce's Recycle Bin rather than permanently destroying it right away.- (blank line)
undelete acc;— restores it using the sameId, exactly reversing thedelete— a real safety net against an accidental mass deletion.System.debug('Restored: ' + acc.Name);— confirms it's back.
Deleting a List at once
List<Account> staleAccounts = [SELECT Id FROM Account WHERE LastActivityDate < :Date.today().addYears(-2)];
delete staleAccounts;
List<Account> staleAccounts = [SELECT Id FROM Account WHERE LastActivityDate < :Date.today().addYears(-2)];— queries every matching record at once.delete staleAccounts;— exactly likeinsertandupdate,deleteaccepts aListfor a single bulk operation — one DML statement removing every matching record, never adeletecall 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;
APEX
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.