+ Start a Discussion
samson sfdcsamson sfdc 

How to insert 500000 records into Object using Batch Apex

I'm New to Apex coding,  I have requirement where I need to insert 500000 records into an object using Batch Apex.
It can be done via Data loader, but I wanted to try it using Batch Apex. guide me please.
Thanks in advance.
Sameer Tyagi SFDCSameer Tyagi SFDC
Hi Samson, 

Here is the sample code for inserting records. Please modify it according to your exact requirement.
global class InsertAccountContactimplements Database.Batchable<sObject>{
     global ExampleBatchClass(){
                // Batch Constructor
     // Start Method
     global Database.QueryLocator start(Database.BatchableContext BC){
     String Query = ''; // Generate your string query on any object here with limit 10000
      return Database.getQueryLocator(Query); //Query is Required on object which you want to run Batch
   // Execute Logic
    global void execute(Database.BatchableContext BC, List<sObject>objlist){
    List<Account> acclist = new List<Account>();
list<Contact> conlist = new list<contact>()
          for(Sobject obj: objlist){
                Account acc = new account();
                acc.name = 'testname';
       insert acclist;
    for(Account acc : Acclist){
          Contact con = new Contact();
           con.lastname = 'testname';
           con.accountid = acc.id;
   Insert conlist;
    global void finish(Database.BatchableContext BC){
         // Logic to be Executed at finish

Thanks & Regards, 
Sameer Tyagi. 
Yogesh KulkarniYogesh Kulkarni
Hi Samson,

If your data is alreaddy present in some other form in SalesForce you should use the apex batch, take a clue directly from salesforce help. If your data sits outside SalesForce use dataloader.

Balaji Chowdary GarapatiBalaji Chowdary Garapati
@samson sfdc:

1)  If you are trying to insert records using batch apex, given that you are having data stored in CSV files, you can use the below link and modify accordingly:


2) If you are trying to insert records directly from an other system which has ability to do an API callout, you can use the Partner API Wsdl from salesforce and consume it in the application which can send call out! For getting Partner API WSDL, go to setup>develop>api>generate partner wsdl. For more info on consuming partner api, go throught the below link:


You can also utilize rest api of salesforce to insert records from an external system.

3) You can also use ETL tools to do that work for you!

4) If you have the data in salesforce itsself and trying to massage the data and insert records into a different object , you can follow the example given by @Sameer Tyagi SFDC

Hope it helps,

Jatinder KumarJatinder Kumar

I was searching the same scenario for using batch to insert records but could not get any specific example for the insert scenario. After reading the salesforce help documentation I created following code and it worked for me. For insert operation I used Iterable<sObject> rather than Database.QueryLocator in start method:


public class VerifyBatchLimit implements Database.Batchable<sObject>, Database.Stateful {
    // Variable to track processed transactions
    public Integer recordsProcessed = 0;
    public Iterable<sObject> start(Database.BatchableContext bc) {
        List<POC_Employee__c> lstEmployee= new List<POC_Employee__c>();
        POC_Employee__c  empl;
        for(Integer i=0; i<50000; i++)
            empl= new POC_Employee__c();
            empl.Employee_Name__c='Employee Name'+i;
        return lstEmployee;
    public void execute(Database.BatchableContext bc, List<POC_Employee__C> employees){
        // process each batch of records
        insert employees;
    public void finish(Database.BatchableContext bc){
        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors,
                            TotalJobItems, CreatedBy.Email
                            FROM AsyncApexJob
                            WHERE Id = :bc.getJobId()];
        System.debug(recordsProcessed + ': records processed!');

Nathanial SchultzNathanial Schultz
This site has a bundle of knowledge. Here I got mostly all types of knowledge. I also have something to share with friends. I also want to write such a beautiful article.
Malika Pathak 9Malika Pathak 9

Hi  samson,

Please find the solution.

global class BatchClassExample implements Database.Batchable<sObject> {
global List<Account> start(Database.BatchableContext BC) {

List<Account> AccList= new List<Account>();
for(Integer i=0;i<500000;i++)
account ac= new account();
String query = 'SELECT Id, Name FROM Account';
return AccList;

global void execute(Database.BatchableContext BC, List<Account> accList) {

try {
Insert accList;

} catch(Exception e) {


global void finish(Database.BatchableContext BC) {
// execute any post-processing operations like sending email

BatchClassExample myBatchObject = new BatchClassExample();
Id batchId = Database.executeBatch(myBatchObject,200);