I'm getting this error in a query in an after update trigger on the contact object. There are 30,123 contacts in our production org. The query is:
List<AggregateResult> results = [SELECT max(National_Serial_Number_Import__C) FROM Contact];
The field is a custom decimal value on the contact object. The query runs once each time the trigger executes. There are a lot of questions about this limit here - I've reviewed the answers and still not seeing what the issue is with my code. Is it that the code also updates a contact? Maybe I should move that code out to a batch?
Also, this code was running fine in production until we ran an upsert which added a few hundred contact records. We went from just under 30,000 contacts to just over 30,000.
For reference, the trigger code is here:
trigger AddNationalSerialNumber on Contact (after update) {
//List<AggregateResult> results = [SELECT max(National_Serial_Number_Import__C) FROM Contact];
//Decimal nsn = (Decimal)results[0].get('expr0');
//Integer nationalSerialNumber = nsn.IntValue();
Decimal nsn = 0;
Integer nationalSerialNumber = 0;
try {
List<AggregateResult> results = [SELECT max(National_Serial_Number_Import__C) FROM Contact];
nsn = (Decimal)results[0].get('expr0');
nationalSerialNumber = nsn.IntValue();
} catch(Exception e) {
//ToDo Handle exception
}
for (Contact newContact : Trigger.new) {
// Access the "old" record by its ID in Trigger.oldMap
Contact oldContact = Trigger.oldMap.get(newContact.Id);
// Check if we have an existing National Serial Number
Decimal existingnsn = 0;
Integer ExistingNationalSerialNumber = 0;
try {
existingnsn = newContact.National_Serial_Number_Import__c;
ExistingNationalSerialNumber = existingnsn.IntValue();
} catch(Exception e) {
//ToDo Handle exception
}
if(oldContact.Member_Status__c == 'Interim'
&& newContact.Member_Status__c == 'Undergraduate'
&& ExistingNationalSerialNumber == 0) {
nationalSerialNumber++;
Contact c = new Contact();
c.id = newContact.id;
c.National_Serial_Number_Import__c = nationalSerialNumber;
update c;
ChapterSpot_Queue__c CSQueue = new ChapterSpot_Queue__c();
CSQueue.Contact__c = newContact.id;
CSQueue.ContactID__c = newContact.id;
CSQueue.National_Serial_Number__c = nationalSerialNumber;
insert CSQueue;
}
}
}