How to fix Cannot have more than 10 chunks error

Today I’m going to discuss about fix for “System.TypeException: Cannot have more than 10 chunks in a single operation. Please rearrange the data to reduce chunking” error.

There are a lot of materials on the web where people suggest solutions to this error, however I couldn’t find official documentation on this limit.

Basically if you are trying to insert or update at least 11 records, let’s say 6 Account records and 6 Contact records, if you mixing them then this error will happen.
To fix this error we need to sort records before the DML operation.

We need to put all Account records first and all Contact records last or vice versa, but they should not be intermixed.
I created two methods to sort chunks. The first method will work fine for update operation but wouldn’t work for insert

public static List<SObject> sortChunks(List<SObject> scope) {
Map<String, List<SObject>> sortMap = new Map<String, List<SObject>>();
for ( SObject rec: scope ) {
String keyPrefix = String.valueOf( rec.Id ).left( 3 );
if (!sortMap.containsKey(keyPrefix)) {
sortMap.put(keyPrefix, new List<SObject>());
}
sortMap.get(keyPrefix).add( rec );
}
List<SObject> flattenedList = new List<SObject>();
for ( String key: sortMap.keySet() ) {
flattenedList.addAll( sortMap.get( key ) );
}
return flattenedList;
}

The second method would work for insert and update cases.

public static List<SObject> sortChunks2(List<SObject> scope) {
Map<String, List<SObject>> sortMap = new Map<String, List<SObject>>();
for ( SObject rec: scope ) {
String keyPrefix = rec.getSObjectType().getDescribe().getName();
if (!sortMap.containsKey(keyPrefix)) {
sortMap.put(keyPrefix, new List<SObject>());
}
sortMap.get(keyPrefix).add( rec );
}
List<SObject> flattenedList = new List<SObject>();
for ( String key: sortMap.keySet() ) {
flattenedList.addAll( sortMap.get( key ) );
}
return flattenedList;
}

Any of these methods can be used as lifehacks or workarounds for the beforementioned error.

Advertisements
This entry was posted in apex, Bugs, DML, Error, example, Governor Limits, lifehack, Posts in English, record, salesforce and tagged , , , , , , , , , . Bookmark the permalink.

2 Responses to How to fix Cannot have more than 10 chunks error

  1. Amir hafeex says:

    List.sort will work

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s