Insert Bulk Account Records

How to insert bulk account records

Execute the below script in developer console to insert bulk account records.

For(integer i=0; i<10; i++) { 
	Account acc = new Account(Name='Dummy Record '+i, AccountNumber='Test'+i, Rating='Hot');
    Insert acc;
}
Script to insert 10000 records once
List<Account> accountsToInsert = new List<Account>();
for (Integer i = 0; i < 10000; i++) {
    Account acc = new Account(
        Name='Dummy Record '+i+2, AccountNumber='Testing'+i, Rating='Hot'
    );
    accountsToInsert.add(acc);
}

insert accountsToInsert;

How the scripts work

The first script loops 10 times and inserts one Account on each pass. The second script builds a list of 10,000 Accounts and inserts the whole list with a single DML statement. Run either one from the Developer Console using Execute Anonymous.

Points to note

  • DML in a loop: the first script runs 10 insert statements. It works, but the limit is 150 DML statements per transaction, so avoid this pattern.
  • The 10,000 row limit: one transaction can process at most 10,000 DML rows. The second script uses exactly that limit. For more records use Batch Apex, the Data Import Wizard or Data Loader.
  • String versus number: in 'Dummy Record '+i+2 the 2 is added as text, so the names look like Dummy Record 02 and Dummy Record 12. If you want to add 2 to the number, write (i+2) in brackets.

Bulk-safe version of the first script

List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 10; i++) {
    accounts.add(new Account(Name = 'Dummy Record ' + i, AccountNumber = 'Test' + i, Rating = 'Hot'));
}
insert accounts;

How to check and clean up

Check the data with SELECT COUNT() FROM Account WHERE Name LIKE 'Dummy Record%'. To remove it, run delete [SELECT Id FROM Account WHERE Name LIKE 'Dummy Record%' LIMIT 10000];. Test data like this is best created in a sandbox.

FAQ

Why is one insert for a list better than many single inserts?
Each insert statement counts against the DML limit. One insert for a list counts once, however many records the list holds.

What happens above 10,000 records?
The transaction stops with a Too many DML rows error. Split the work across several transactions with Batch Apex.

Leave a Reply