While working on requirement where we have to perform DML on multiple object dynamically by using sobject, we got below error:
"System.TypeException: Cannot have more than 10 chunks in a single operation. Please rearrange the data to reduce chunking."
This kind of error appears if your list of sobject contains more than 10 types of object records or record of objects are not ordered based on object. For example if you are adding lead, account and contact record to sobject list by using below format:
Lead1,Account1,Contact1,Lead2,Account2,Contact2,Lead3,Account3,Contact3,Lead4,Account4,Contact4
This will be considered as 12 chunks on sobject and while performing DML, you will get this error.
If you want to avoid it, then rearrange the records in below format:
Lead1,Lead2,Lead3,Lead4,Account1,Account2,Account3,Account4,Contact1,Contact2,Contact3,Contact4
This sequence of records will be considered as 3 chunks and is allowed in single DML operation.
Execute below script and you will get this error:
List<sObject> sbList=new List<sObject>();
for(integer i=0;i<10;i++){
sblist.add(new Lead(lastname='Test Leat'+i,company='test company'+i));
sblist.add(new Account(name='Test Account'+i));
sblist.add(new Contact (lastname='test name'+i,email='test@gmail.com'+i));
}
insert sblist;
Ways to resolve this kind of error:
- Rearrange the records in list so that all records belonging to one object are stored together in list.
List<sObject> sbList=new List<sObject>();
for(integer i=0;i<10;i++){
sblist.add(new Lead(lastname='Test Leat'+i,company='test company'+i));
for(integer i=0;i<10;i++){
sblist.add(new Account(name='Test Account'+i));
for(integer i=0;i<10;i++){
sblist.add(new Contact (lastname='test name'+i,email='test@gmail.com'+i));
- Sort the sobject list before performing DML
List<sObject> sbList=new List<sObject>();
for(integer i=0;i<10;i++){
sblist.add(new Lead(lastname='Test Leat'+i));
sblist.add(new Account(name='Test Account'+i));
sblist.add(new Contact (lastname='test name'+i,email='test@gmail.com'+i));