When I execute the following code

List<SObject> toSave = new List<SObject>();
for(integer i = 0; i < 100; i++ )
{
    BB_A__c bba = new BB_A__c(
        x__c = 'testx',
        y__c = 'testy'
    );
    if(i == 5)
    {
        bba.x__c = 'bartek';
    }
    toSave.add(bba);
     
    BB_B__c bbb = new BB_B__c(
        x__c = 'testx',
        y__c = 'testy'
    );
    if(i == 7)
    {
        bba.y__c = 'bartek';
    }
    toSave.add(bbb);    
}
insert toSave;

You receive the following error:
Execution Failed. System.TypeException: Cannot have more than 10 chunks in a single operation. Please rearrange the data to reduce chunking.

but after execution of this script:

List<SObject> toSave = new List<SObject>();
for(integer i = 0; i < 100; i++ )
{
    BB_A__c bba = new BB_A__c(
        x__c = 'testx',
        y__c = 'testy'
    );
    if(i == 5)
    {
        bba.x__c = 'bartek';
    }
    toSave.add(bba);
}
 
for(integer i = 0; i < 100; i++ )
{   
    BB_B__c bbb = new BB_B__c(
        x__c = 'testx',
        y__c = 'testy'
    );
    if(i == 7)
    {
        bbb.y__c = 'bartek';
    }
    toSave.add(bbb);
     
}
insert toSave;

everything goes smoothly. This is because when you insert a list with multiple objects, the data type cannot change more than 10 times. Do not ask why, this is SALESFORCE.
But there is a simple solution:
You have to sort the list that you want to add. Because the standard List.sort() method sorts collection by SObject labels then you will have all objects grouped by SObject label that equals to sobject type:). Here is a working example:

List<SObject> toSave = new List<SObject>();
for(integer i = 0; i < 100; i++ )
{
    BB_A__c bba = new BB_A__c(
        x__c = 'testx',
        y__c = 'testy'
    );
    if(i == 5)
    {
        bba.x__c = 'bartek';
    }
    toSave.add(bba);
     
    BB_B__c bbb = new BB_B__c(
        x__c = 'testx',
        y__c = 'testy'
    );
    if(i == 7)
    {
        bba.y__c = 'bartek';
    }
    toSave.add(bbb);
     
}
 
toSave.sort(); // <-- this line fixes our issue:):):)
 
insert toSave;

Conclusion

Here is the method I found one of the answers from the Salesforce developers community by Julien Castelluci

Source:
https://bartoszborowiec.wordpress.com/2014/06/15/execution-failed-system-typeexception-cannot-have-more-than-10-chunks-in-a-single-operation-please-rearrange-the-data-to-reduce-chunking/

Leave a Comment