I am getting this error when I tried to set read access Level of all custom fields of account object to a permission set.

  • Error:

Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: duplicates value on record with id: : []

// get all api name fields
List<String> fields = new List<String>();

String type='Account';
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Schema.SObjectType leadSchema = schemaMap.get(type);
Map<String, Schema.SObjectField> fieldMap = leadSchema.getDescribe().fields.getMap();

for (String fieldName: fieldMap.keySet()) {

//permission set

Set<String> permissioinSetsLabels = new Set<String> {
    'BCP BDN Utilities non productive'

List<PermissionSet> pemissionSetList = [SELECT Id, Name, Label FROM PermissionSet WHERE Label IN :permissioinSetsLabels];
List<FieldPermissions> fpList = new List<FieldPermissions>();
String pcValue = '__pc';
Set<String> sStrings = new Set<String>(fields);
for(PermissionSet ps : pemissionSetList){

    for(String fieldsIterate: sStrings){
        if(!fieldsIterate.contains(pcValue) && fieldsIterate.contains('__c') && fieldsIterate!=NULL){
        FieldPermissions fp = new FieldPermissions();
        Boolean checkValue= fp.PermissionsRead;
        System.debug('el valor es: '+checkValue);
        if(checkValue == false){
            System.debug('ENTRO AL IF');
            fp.SobjectType = 'Account';
            fp.Field = 'Account'+'.'+fieldsIterate;
            fp.PermissionsRead = true;
            fp.ParentId = ps.Id;

        Set<FieldPermissions> myset = new Set<FieldPermissions>();
        List<FieldPermissions> result = new List<FieldPermissions>();
  if(!fpList.isEmpty()) insert result;
      System.debug('La lista es: '+fpList);}catch(Exception e){
          System.debug('el error es: '+e);

1 Answer 1


I reproduced the error. You'll want to use upsert instead of insert. Try the code below:


upsert result; //per david’s point you dont need to check for empty here


  • Hi guys, thanks for your response, but when I use upsert is the same error "System.DmlException: Upsert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: <unknown> duplicates value on record with id: <unknown>: []" Jan 10, 2021 at 23:20
  • 1
    @PeterSmith do you have another idea? Jan 11, 2021 at 2:54
  • Hmm, open developer console’s anonymous apex in a sandbox and be sure you are truly doing upsert, not insert. Upsert worked for me, but insert yields the error you cited. Beyond that I’m unsure. Be sure you download/analyze the correct log too Jan 11, 2021 at 5:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .