i am suddenly getting the following error in apex trigger :

"System.LimitException: Too many query rows: 50001"

Here is my apex trigger code :

trigger SetAmountfromOTTtoSFDC on Opportunity (Before Insert, Before Update) {

Map <string, Id> AccountTextIdMap = new Map<String,Id>();
Map <string, Id> ContactTextIdMap = new Map<String,Id>();

if(Trigger.IsInsert || Trigger.IsUpdate){
    List<Account> AccList = [select Id, Name, AccountId__c from Account];
    for(Account ac : AccList){
        AccountTextIdMap.put(ac.AccountID__c, ac.id);
    List<Contact> ConList = [select Id, Contact_ID__c from Contact];
    for(Contact con : ConList){
        ContactTextIdMap.put(con.Contact_ID__c, con.id);

    for(Opportunity op : Trigger.New){

        if(op.AdrAccountSearchKey__c != Null && op.AccountId == Null){
            op.AccountId = AccountTextIdMap.get(op.AdrAccountSearchKey__c);

        if(op.AdrContactSearchKey__c != Null && op.Contact__c == Null){
            op.Contact__c = ContactTextIdMap.get(op.AdrContactSearchKey__c);

I am using this trigger to set up the records which all are coming from other system using synchronization

i think Batch is very useful to this case but i am not sure how to do it, can somebody help me out


1 Answer 1

 List<Account> AccList = [select Id, Name, AccountId__c from Account];
 List<Contact> ConList = [select Id, Contact_ID__c from Contact];

Might chances that these query are causing this issue. So you can update here to something like

Set<Id> accIdset = new Set<ID>();
Set<Id> conIdset = new Set<ID>();
for(Opportunity op : Trigger.New){
     if(op.AdrAccountSearchKey__c != null)

      if(op.AdrContactSearchKey__c != null)

and then in your query update them and use this set

List<Account> AccList = [select Id, Name, AccountId__c from Account WHERE AccountId__c  IN: accIdset];

List<Contact> ConList = [select Id, Contact_ID__c from Contact WHERE Contact_ID__c IN: conIdset];

This will reduce your number of records still with very large data you might hit the limit.

  • Thanks Tushar !! Can we use Batch apex if Limit is hit ?
    – Nihar
    Dec 14, 2016 at 11:03
  • @Nihar Sure you can but it depends on complete requirement because you will not get real time update. Also if it solve your problem then you can accept the answer. Dec 14, 2016 at 11:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .