How To Insert Over 10,000 Records Using Apex

Now this is very common use case and everybody will think of batch apex, which is obviously correct. But suppose you have below use case.

When user insert an Account, you need to insert 15K related Contacts.

Now this is tricky, why? Because for sure you will query Account in start method and build your logic in Execute to build the list of 15K related contacts. There is a catch on this. As start has only one record the number of batches will be only one and we have the limitation of 10K per transaction.

So, here is a quick solution to this (there could be another one as well).

Now build the contact list in the account trigger and pass that list to conatct batch constructor and in start method just return list of Sobject.

PFB one sample code (Note: this is not a refined code, just a rough written code to give you an idea)

Schedule Class:

global class ScheduleContactInsert implements Schedulable {
 
    global void execute(SchedulableContext sc) {
        List<Contact> contactsToInsert = new List<Contact>();
 
        // Build your list of contacts here
        for (Integer i = 0; i < 15000; i++) {
            Contact newContact = new Contact(
                FirstName = 'ContactFirstName' + i,
                LastName = 'ContactLastName' + i,
                Email = 'contact' + i + '@example.com'
                // Add other necessary fields
            );
 
            contactsToInsert.add(newContact);
        }
 
        // Start the batch job and pass the list of contacts
        BulkInsertBatch batchJob = new BulkInsertBatch(contactsToInsert);
        Database.executeBatch(batchJob, 200); // Adjust the batch size
    }
}

Batch Class:

global class BulkInsertBatch implements Database.Batchable<sObject> {
 
    global List<Contact> contactsToInsert;
 
    global BulkInsertBatch(List<Contact> contactsToInsert) {
        this.contactsToInsert = contactsToInsert;
    }
 
    global sObject[] start(Database.BatchableContext BC) {
        // Return the list of contacts to be inserted
        return contactsToInsert;
    }
 
    global void execute(Database.BatchableContext BC, List<Contact> scope) {
        // Process the list of contacts and insert them
        try {
            insert scope;
        } catch (Exception e) {
            // Handle exceptions as needed
        }
    }
 
    global void finish(Database.BatchableContext BC) {
        // Perform any post-processing if needed
    }
}