Inserting multiple records at once is a best practice for optimizing system efficiency and staying within governor limits. When you insert records one at a time, each insertion counts as a separate DML (Data Manipulation Language) operation, quickly consuming system resources and potentially hitting Salesforce governor limits. By adding multiple records to a list and inserting them in a single transaction, you can significantly reduce the number of DML operations used and improve code performance.

How to insert multiple records at a time?

For example, in the insert100 class above, multiple records of the custom object Testing__c are added to a list called lstTesting. This list is then inserted all at once with a single insert statement (insert lstTesting). This approach not only streamlines the code but also ensures it is scalable, as it minimizes DML calls. Following this bulk insertion technique is crucial in Salesforce for handling larger data sets efficiently while maintaining compliance with Salesforce’s governor limits.

public class insert100
{
public void m1()
{
List<Testing__c> lstTesting = new List<Testing__c>();
Testing__c objTest;
objTest = new Testing__c(name='Testing1',city__c='City1');
lstTesting.add(objTest);
objTest = new Testing__c(name='Testing2',city__c='City2');
lstTesting.add(objTest);
objTest = new Testing__c(name='Testing3',city__c='City3');
lstTesting.add(objTest);
objTest = new Testing__c(name='Testing4',city__c='City4');
lstTesting.add(objTest);
objTest = new Testing__c(name='Testing5',city__c='City5');
lstTesting.add(objTest);
insert lstTesting;
}
}
* In order to execute above class , go to System Log and execute as follows
insert100 obj=new insert100();
obj.m1();

 

Inserting list of records through For loop

public class insert100
{
public void m1()
{
List<Testing__c> lstTesting = new List<Testing__c>();
Testing__c objTest;
for(Integer i=6;i<=100;i++)
{
objTest=new Testing__c(name='Testing'+string.valueof(i),city__c='City'+string.valueof(i));
lstTesting.add(objTest);
}
insert lstTesting;
}
}
* In order to execute above class , go to System Log and execute as follows
insert100 obj=new insert100();
obj.m1();

 

Performing the pagination on VF page (display 2 records per page)

Visualforce page:

<apex:page sidebar="false" standardController="Testing__c" recordSetVar="records" extensions="PageDataClass">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:pageBlockTable value="{!records}" var="r">
<apex:column headerValue="Name">
{!r.Name}
</apex:column>
<apex:column headerValue="City">
{!r.City__c}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlockSection>
<apex:commandLink value="previous" action="{!previous}"/> |&nbsp;
<apex:commandLink value="next" action="{!next}"/>
</apex:pageBlock>
</apex:form>
</apex:page>

Apex class:

public with sharing class PageDataClass {
public PageDataClass(ApexPages.StandardSetController controller) {
controller.setpagesize(2);
}
}