+ Start a Discussion
Lee SinLee Sin 

Do I Need to use Batch Apex here, if so how can I use batch apex?

I have two types of Account, advisor and client.
Each advisor has 3000 clients.  I want to get the 75 random clients and use their ids to create 75 tasks. 

//1 query 36 result rows
List<Account> advisors=[select id,account_type__c,client_territories__c from Account where account_type__c='advisor'];

for(Account a : advisors)
    //result rows too large, over 50000
    //For each advisor, create a list of its clients Account
    List<Account> clients=[select id from Account where client_territories__c=:a.client_territories__c];
    //Here I want to randomly pick 75 Account Ids and use that as whatid to create 75 Tasks
    //If I use the "Limit" Key word in the query, it will not generate random records right?

Best Answer chosen by Lee Sin
Jack, the field account_Type__c, does it contain "client" for client records ? 

All Answers

Jack, the field account_Type__c, does it contain "client" for client records ? 

This was selected as the best answer
Lee SinLee Sin
@Hargobind_Singh  Yes.
I modified my code to avoid using query inside a for loop.
But Still got error.
//This map stores the territory name and the client Accounts IDs in that territory
Map<String,List<ID>> AdvisorClientsMap=new Map<String,List<ID>>();

//Get 40 advisor Account records
List<Account> advisors=
    [select id,client_territories__c,account_type__c,Monthly_Activity_Reporting__c from Account where Monthly_Activity_Reporting__c=true
     and (account_type__c='provider' or account_type__c='advisor')];

//Stores 40 territories in a List
List<String> advisorTerritories=new List<String>();

List<ID> advisorIDs=new List<ID>();

//put territories into the list
for(Account advisor : advisors)

//the below query gives me "Too many query rows: 50001" error
//So what can I do here to avoid the limit
//get all clients order by territory
List<Account> clients=[select ID,client_territories__c from Account where client_territories__c in :advisorTerritories and id not in :advisorIDs order by client_territories__c];

//Use this list to store client Accounts into map
List<Account> clientList=new List<Account>();

//previous territory name
String previousTerritory=clients[0].client_territories__c;

for(Account client : clients)
        clientList=new List<Account>();

Line 23 gives me too many result rows 50001