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;
  1. Account acc = [SELECT Id FROM Account WHERE Name = 'Northwind Traders' LIMIT 1]; — queries the record, including its Id.
  2. 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.

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);
  1. Account acc = [SELECT Id FROM Account WHERE Name = 'Northwind Traders' LIMIT 1]; — queries the record.
  2. delete acc; — moves it to Salesforce's Recycle Bin rather than permanently destroying it right away.
  3. (blank line)
  4. undelete acc; — restores it using the same Id, exactly reversing the delete — a real safety net against an accidental mass deletion.
  5. 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;
  1. List<Account> staleAccounts = [SELECT Id FROM Account WHERE LastActivityDate < :Date.today().addYears(-2)]; — queries every matching record at once.
  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;

APEX

Delete and Undelete Quiz

1. What happens to a record immediately after delete?

Log in to submit the quiz and save your score.

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.