I have a custom object set up and a scheduled task each night which needs to delete all the existing records and insert a load of new ones. It has been running fine for a while but now we have more data, so the initial SELECT which retrieves the Id's of the objects to be passed to the delete() API call is taking close to or over the 2 minute timeout. I thought it might be to do with the recycle bin so I have cleared them all out of there and adjusted the code to bypass the recycle bin, but the problem remains.

Currently the process is:

QueryResult sqr = SvcBinding.query("SELECT Id FROM MyCustomObj__c");
while (sqr.size > 0) {
    string[] ids = sqr.records.Select(b => b.Id).ToArray();
    DeleteResult[] dr = SvcBinding.delete(ids);

    // Empty deleted records from recycle bin
    string[] successIds = Array.FindAll(dr, res => res.success).Select(b => b.id).ToArray();

    if (sqr.done)
        sqr = SvcBinding.queryMore(sqr.queryLocator);

and then the new data is read from our internal DB and new MyCustomObj's inserted into SF via the same SOAP API.

Is there a better way of mass deleting the records, without having to select the Id's first, given that there is no filtering needed, just need to delete all records of MyCustomObj?

  • 1
    Out of curiosity, how many records are generated daily?
    – IvanR
    Commented Nov 13, 2014 at 15:35
  • 1
    Any reason you can't just run this as a scheduled batch directly in SF? Commented Nov 13, 2014 at 16:12
  • @Ivan It is currently at around 40,000 objects to be deleted daily
    – RossJ
    Commented Nov 13, 2014 at 16:49
  • @BritishBoyinDC I may look into that, but wanted it to be part of the same process as inserting the new records (which happens after the code above). It isn't ideal for us to run something directly in SF and then have this process run separately afterwards to insert the new data.
    – RossJ
    Commented Nov 13, 2014 at 16:50
  • 2
    Alternatively, consider using Bulk API - it is an async API so timeouts won't be an issue.
    – IvanR
    Commented Nov 14, 2014 at 9:47

2 Answers 2


SalesForce themselves have suggested adding in ORDER BY Id as there are certain optimisations built in around the fact that Ids are ordered. The first run after making this change successfully avoided timing out, I will see how it runs over the next few days and mark this as an answer if it's helped.

  • Seems to have done the trick. For now.....
    – RossJ
    Commented Nov 19, 2014 at 9:48

Can you try this line of code. List myCustomList = [SELECT Id FROM MyCustomObj__c]; if(myCustomList.size() >0) { delete myCustomList; }

  • 1
    Author's solution is not in Apex...
    – IvanR
    Commented Nov 13, 2014 at 15:43
  • Yes sorry, this is using the SOAP API in C#
    – RossJ
    Commented Nov 13, 2014 at 16:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .