Suppose that you have created some records on any object and you want to delete all record at one time.
Here is code that you can run from your developer console or apex program.
List l = [SELECT id from Account];
delete l;
Using this code you can delete records from your standard or custom object.
Before execute NOTE : that this code will delete all record at one time . No record will be there on object after you execute this code.
Watch the following video where I have implemented and explained same concept
How the code works
The first line queries the Ids of all Accounts into a list. The second line deletes the whole list in one DML statement. Replace Account with any other object name to delete its records.
Limits and risks
- A single transaction can process at most 10,000 DML rows, and a query returns up to 50,000 rows. With more records, this code fails.
- The delete is not confirmed. Deleted records stay in the Recycle Bin for 15 days, and then they are gone.
- Deleting a parent record also deletes its children, such as the Contacts of an Account.
- Run this only in a sandbox, or in production only after you take a backup.
Version for large volumes
public class DeleteAllRecordsBatch implements Database.Batchable<SObject> {
private String objectName;
public DeleteAllRecordsBatch(String objectName) {
this.objectName = objectName;
}
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id FROM ' + String.escapeSingleQuotes(objectName));
}
public void execute(Database.BatchableContext bc, List<SObject> scope) {
delete scope;
}
public void finish(Database.BatchableContext bc) {}
}
// Run it from the Developer Console:
Database.executeBatch(new DeleteAllRecordsBatch('Account'), 200);The batch deletes the records in chunks of 200, so it is not stopped by the 10,000 row limit. You can follow its progress in Setup under Apex Jobs.
FAQ
Can I delete without Apex?
Yes. Data Loader and the Mass Delete Records tool in Setup can delete records of many objects.
Can I get the records back?
Within 15 days, yes. Open the Recycle Bin and restore them.