How to avoid DML Insert/Update Limit of 10,000 rows when running anonymous apex?

  • Is there any way to bulkify an insert/update operation performed from anonymous apex?

    For instance, if I have a script that builds a list of 15,000 records that need to be updated, is there any way to avoid hitting the "Too many DML rows: 10001" error when trying to insert/update?

  • Doug B

    Doug B Correct answer

    8 years ago

    For a quick and dirty approach if I have more than 10,000 rows to update through anonymous apex I will sometimes do something like this

    List<Thing__c> things = [select id from thing__c where status__c = 'Old value' limit 10000];
    for (Thing__c thing : things) {
       // make changes
       thing.status__c = 'New Value';
    }
    update things;
    

    Then run the script twice or whatever. This relies on the change you're making being something that you can filter in the where condition. Also this will get dull if there are many tens of thousands of records to update and you have to kick off the script again and again.

    Thanks Doug. Given my time constraints, and my not really wanting to write a batchable class for this one-off data cleanup task, I ended up doing exactly what you suggested. Thanks!

    @BBP27 You can also open multiple dev console/workbench instances and run jobs in parallel - I often do that if I need to generate 100k or so records in my scratch orgs.

    How would you identify which 10k records were returned in the query? And how would you ensure that the remaining 10k records would be returned the next time you run the script?

    @AyushGoyal each time you run the query you pick up some 10k records that match your criteria, and you update them. They no longer match the criteria, so they won't be selected when you run the query again.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used