function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
karimulla salesforcekarimulla salesforce 

Dml Exception while inserting multiple records using a for loop

for(integer i=1; i<=10; i++){
     
Account a = new account();
  a.name ='sha';
  a.phone='123';
  a.annualrevenue=9096;
  insert a;
    
}

hi, iam going to insert a multiple records using a forloop on the account object, but getting an dml exception.


User-added image
//if tried for contact object , it is getting work , may i know the reason behind it...

Thanks 
karimulla syed
SarvaniSarvani
Hi Karimulla,

I guess the error is due to duplicate rules enforced in your org. Try navigating to Setup-> Duplicate Rules-> Check if there is any rule on Account.
As there is no such rule which is meeting the criteria on contact duplicate rules your records are inserted on contact object.

More on duplicate rules:
https://help.salesforce.com/articleView?id=duplicate_rules_map_of_reference.htm&type=5 (https://help.salesforce.com/articleView?id=duplicate_rules_map_of_reference.htm&type=5)

Hope this helps ! Please mark as best if it does.

Thanks
NehaBNehaB
Hello karimulla ,

You are facing this issue because of the Rules defined in salesforce for managing Duplicate Accounts . 

A matching rule defines how duplicate records are identified in duplicate rules and duplicate jobs. Salesforce provides standard matching rules for business and person accounts, contacts, and leads. You can also create custom matching rules.

Refer Standard Account Matching Rule (https://help.salesforce.com/articleView?id=matching_rules_standard_account_rule.htm&type=5) . 

Since in your case you are using the same Account name for all the Accounts you are creating inside the loop , you are getting this Error .
Try changing the name , For example 
for(integer i=1; i<=10; i++)
{ Account a = new account(); 
a.name ='sha'+i;  // Append i at the end so that Account name is differenr each time
a.phone='123'; 
a.annualrevenue=9096;
insert a; }

Also , I would suggest that never Insert inside a for loop . you may run into limits soon . 
List<Accounts> acc = new List<Accounts>();
for(integer i = 1; i <= 10; i++)  { 
Account a = new account(); 
a.name ='sha'+i;  
a.phone='123'; 
a.annualrevenue=9096;
acc .add(a);
 }
insert acc;


 
sachinarorasfsachinarorasf
Hi Karimulla,

I have gone through your problem.
 
List<Account> accountList = new List<Account>();
for(integer i=1; i<=10; i++){
Account a = new account();
  a.name ='sha'+i;
  a.phone='123323240'+i;
  a.annualrevenue=9096;
  accountList.add(a);
}
insert accountList;

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Sachin Arora
SfDeveloperSfDeveloper
How to print  ID's in this case?