[SalesForce] How to delete 10K records in Salesforce via Apex

This question might be more towards the approach than the technical side. The scenario is the following:

I have to run a scheduler to delete some records. The record size is always going to be less than 10,000.

Can I retrieve all the results in a list like:

List <sObject> listsObject = [Select Id from sObject where Test__c = true Limit 9000];
Delete listsObject;

Will this be able to delete all the records in the list?! Or will this only delete the 200 records?

Also, I know I could follow the batch Apex Approach but I want to know first if this will work, and if this certainly works I dont have to write Batch Apex and then schedule it.

Best Answer

Yes, it will work just fine. You can even write it in 1 line:

delete [Select Id from sObject where Test__c = true Limit 9000];

It will fail the whole delete operation though if there's any kind of problem (like "before delete" trigger that makes some extra checks and complains). You can set it to "delete what you can, I'll deal with errors separately" by using another version of delete that takes an extra parameter.

Database.delete([Select Id from sObject where Test__c = true Limit 9000], false);
Related Topic