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
Randy OrtanRandy Ortan 

how can Insert 5 Accounts with at least 1 related Opportunity. Using SOQL in salesfroce

Arun Kumar 1141Arun Kumar 1141
Hi Randy,

To insert 5 accounts with at least 1 related opportunity using SOQL in Salesforce, you can follow these steps:
Prepare the data for the 5 accounts and related opportunities that you want to insert
List<Account> accountsToInsert = new List<Account>();

for (Integer i = 1; i <= 5; i++) {
    Account newAccount = new Account(
        Name = 'Account ' + i
        // Additional fields for the Account

    Opportunity newOpportunity = new Opportunity(
        Name = 'Opportunity ' + i,
        AccountId = newAccount.Id,
        // Additional fields for the Opportunity
        // You can also set the opportunity's StageName, CloseDate, Amount, etc.

    // Associate the opportunity with the account
    newAccount.Opportunities = new List<Opportunity>{newOpportunity};


// Insert the new accounts and related opportunities
insert accountsToInsert;

In this code, we create a list accountsToInsert to hold the new account records. We iterate through a loop to create the new accounts and related opportunities. For each iteration, we create an account and an opportunity, set the necessary fields, and associate the opportunity with the account by adding it to the Opportunities relationship field. Finally, we insert the new account records using the insert statement.

If this helps you please mark it as a best answer,
Randy OrtanRandy Ortan
HI @Arun Kumar

when I am executing your code it was showing one Error Field is not writeable: Account.Opportunities.

can you please help me with this error
Mahesh GorrepatiMahesh Gorrepati
CHECK the code Below:-  here , we used  SOQL Queries to create Opportunity records. We don't need to any SOQL feom create the Relarted OPPortunities.But,you mentioned it in the Query, for that reason i prepared the below the code
Note:- ANy Optimaisation is reuires, Please SUggest

public  class   accountswithrelatedOpps{

public static void  createaccounts () {
        list< account> lstaccounts = new list<account>();
            for(integer i=1;i<=5;i++){
               Account Acc = new Account ();
                 'Randy Ortan';
set<id> accountids = new set <id>();
Database.Savresult[] Results = Database.insert(lstaccounts, False);
           for( Database.Saveresult res : Results){
                      System.debug('' + Res.getID);
                       if(Database.Error err :  res,getError()){
                                System.debug(''+ err.GetMessage());
list<account> lstaccounts =[select id,name from account where id in: accountids];
list<OPPortunity> lstopps = new /,OPportunity >();
for( Integer j=0;j<=4;j++){
 Opportunity Opp = new OPPortunity ();
        = lstaccounts[0].name+'OPP';
               OPP.closedate =;
             opp.accountid = lstaccounts[0];
               lstopps .add(Opp);
insert lstopps;

SwethaSwetha (Salesforce Developers) 
HI Randy,
Try below code
public class AccountOpportunityHandler {
    public static void createAccountsAndOpportunities() {
        List<Account> accounts = new List<Account>();
        List<Opportunity> opportunities = new List<Opportunity>();
        // Create 5 Account records
        for (Integer i = 0; i < 5; i++) {
            Account account = new Account(Name = 'Test Account ' + i);
        insert accounts;
        // Create 1 Opportunity record for each Account record
        for (Account account : accounts) {
            Opportunity opportunity = new Opportunity(Name = 'Test Opportunity', AccountId = account.Id,StageName = 'Prospecting', CloseDate =;
        insert opportunities;

Execute this by running below in dev console


If this information helps, please mark the answer as best. Thank you