Insert Bulk Accounts and 5 Contacts to Each Account

Code Snippet to Bulk Insert Accounts and 5 Contacts to Each Account.

Execute the below script in developer console. It will create 5 Accounts records and each Account have 5 Contacts.

For(integer i=0; i<5; i++) { 
	Account acc = new Account(Name='Bulk Account '+i, AccountNumber='919102'+i, Rating='Hot');
	Insert acc;
    For(integer j=0; j<5; j++) { 
        Contact con = new Contact(LastName=acc.Name +' Contact '+j, AccountId=acc.Id);
		Insert con;
    }
}

How the script works

Run this script in the Developer Console: open Debug, then Open Execute Anonymous Window, paste the code and click Execute. The outer loop creates 5 Accounts. After each Account is saved, the inner loop creates 5 Contacts linked to it through AccountId, so you end up with 5 Accounts and 25 Contacts.

Problem in this version

The script runs an insert statement inside both loops. That is 5 + 25 = 30 DML statements. Salesforce allows 150 DML statements in one transaction, so the script works for this small example, but it fails as soon as you try 100 Accounts. It is also a bad habit to carry into triggers and classes.

Bulk-safe version

List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 5; i++) {
    accounts.add(new Account(Name = 'Bulk Account ' + i, AccountNumber = '919102' + i, Rating = 'Hot'));
}
insert accounts;

List<Contact> contacts = new List<Contact>();
for (Account acc : accounts) {
    for (Integer j = 0; j < 5; j++) {
        contacts.add(new Contact(LastName = acc.Name + ' Contact ' + j, AccountId = acc.Id));
    }
}
insert contacts;

This version builds a list for each object and inserts the whole list at once, so it uses only 2 DML statements no matter how many records you create.

How to check the result

Run this query in the Query Editor to see each Account with its Contacts:

SELECT Name, (SELECT Name FROM Contacts) FROM Account WHERE Name LIKE 'Bulk Account%'

To remove the test data, run delete [SELECT Id FROM Account WHERE Name LIKE 'Bulk Account%'];. Deleting an Account also deletes its Contacts. Use a sandbox or a developer org for test data.

FAQ

Why does the Contact need the Account Id first?
The Account must be saved before it gets an Id. Only then can a Contact point to it through AccountId.

What is the limit on DML statements?
150 DML statements and 10,000 DML rows per transaction.

Leave a Reply