Salesforce

Salesforce Apex System.TypeException – Cannot have more than 10 chunks in single operation. Please rearrange the data to reduce chunking.

Solution: Please rearrange the data to reduce chunking.

When I am trying to insert parent and child in same transaction while preparing the list of records to be inserted in a loop, I am getting this error as System.TypeException “Cannot have more than 10 chunks in a single operation. Please rearrange the data to reduce chunking.”

Here is sample erroring apex code snippet.

List<SObject>  lstSObj = new List<SObject>();
Integer inputSize = JSonInputString.size(); // assume 10
for(integer i = 0; i < inputSize ; i ++) {
    lstSObj.add(new Parent(name='DoozySpot'+i, company='DoozySpot'+i));

    lstSObj.add(new Child(name='DZ Child'+i));
}

insert lstSObj;

The lstSObj is considered is having records as
Parent, Child, Parent, Child, Parent, Child…. 10 times.

This is making my list contains more than 10 different Sobjects so more than 10 chunks.

This kind of error occurs when my list of sobject contains more than 10 types of object records or record of objects are not ordered based on type of sobject added to the list.

For Ex:

We can only create 10 separate insert chunks, and every time you alternate creates a new chunk. Consider the following list, which counts for 12 chunks instead of 2:

insert new List<SObject> {
    new Account(Name='Name1'), new Contact(Name='Contact1'),
    new Account(Name='Name2'), new Contact(Name='Contact2'),
    new Account(Name='Name3'), new Contact(Name='Contact3'),
    new Account(Name='Name4'), new Contact(Name='Contact4'),
    new Account(Name='Name5'), new Contact(Name='Contact5'),
    new Account(Name='Name6'), new Contact(Name='Contact6')
};

We can sort out this issue 2 ways

  1. Add all of the similar kind of records at one after another type
  2. Sorting the records in the list.

  • Reorder the records related to each object while adding to the list itself
List<SObject>  lstSObj = new List<SObject>();
Integer inputSize = JSonInputString.size(); // assume 10
for(integer i = 0; i < inputSize ; i ++) {
    lstSObj.add(new Parent(name='DoozySpot'+i, company='DoozySpot'+i));
}
for(integer i = 0; i < inputSize ; i ++) {
    lstSObj.add(new Child(name='DZ Child'+i));
}

insert lstSObj;
  • Sorting the records in the apex List before performing DML
List<SObject>  lstSObj = new List<SObject>();
Integer inputSize = JSonInputString.size(); // assume 10
for(integer i = 0; i < inputSize ; i ++) {
    lstSObj.add(new Parent(name='DoozySpot'+i, company='DoozySpot'+i));

    lstSObj.add(new Child(name='DZ Child'+i));
}

//Sorting before Apex DML
lstSObj.sort();
insert lstSObj;

This has fixed my problem, hope it helps someone.

Leave a Reply

Your email address will not be published. Required fields are marked *