function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jonathan Hsu 4Jonathan Hsu 4 

Create a list of accounts with opportunities efficiently

I need to be able to make a list of accounts and an opportunity within each newly created account. What's the most efficient way to do this?

Currently, my plan is to create a List<Account> and do a Database.insert() then for each Id, add an opportunity to List<Opportunity> then do another Database.insert().

Is there a better way?
Abhishek BansalAbhishek Bansal
Hi Jonathan,

Yes you need to insert the accounts first in order to link it with the opportunity. After that, you can insert the opportunities.
Sample code is added below:
List<Account> listOfAccountsToInsert = new List<Account>();
Account newAccount;
for(Integer i=1; i<=5; i++) {
	newAccount = new Account();
	newAccount.Name = 'New Account' + i;
insert listOfAccountsToInsert;

List<Opportunity> listOfOppsToInsert = new List<Opportunity>();
Opportunity newOpp;
for(Account acc : listOfAccountsToInsert) {
	newOpp = new Opportunity();
	newOpp.Name = acc.Name;
	newOpp.AccountId = acc.Id;
	newOpp.Stage = 'New';
	newOpp.CloseDate =;
insert listOfOppsToInsert;

Let me know if you need any further help or information.

Abhishek Bansal
Jonathan Hsu 4Jonathan Hsu 4
Hey Abhishek,

So when you do the insert statement on listOfAccountsToInsert, the resulting IDs are injected into the list of sObjects? If so, that makes things really simple. I thought I had to iterate over the Database.SaveResult to get the IDs and manually map them to listOfAccountsToInsert.