I actually need a soql query to fetch those case records in which the incoming emails from email to case are more than one in the related list of case. One criteria is that the subject of the email contains word like 'ref'. What I wrote is this..

List<case> caserecord=[SELECT Id, threadID__c FROM Case WHERE  SuppliedEmail !=null AND isClosed=false];

but i think it will throw Governor limit error of more than 50000 records. So, kindly let me know the best query to resolve this issue.

I also tried like this:-

List<EmailMessage> incomingemails= [Select Id,ParentId,ToAddress,Subject,Incoming,TextBody from EmailMessage WHERE Subject LIKE '%ref%' AND Incoming=:true];
for(EmailMessage en:incomingemails){

You could achieve this using a single SOQL.

Integer count = Limits.getLimitQueryRows() - Limits.getQueryRows();

List<Case> caseList = [SELECT Id, threadID__c, (SELECT Id,ParentId,ToAddress,Subject,Incoming,TextBody FROM EmailMessages) 
                       FROM Case 
                       WHERE SuppliedEmail != null 
                          AND isClosed = false 
                          AND Id IN (SELECT ParentId 
                              FROM EmailMessage 
                              WHERE Subject LIKE '%ref%' AND Incoming = true)
                       LIMIT :count];

If you need only the Case records then remove the inner query. Please have a look at Limit class.

  • @reshma....best regards from my side in answering to the the issue. I think your query will work. Because my requirement is to get the case records in which the email in the related list is more than one. – vineet Jun 5 '17 at 9:01
  • @reshma--just want to ask the LIMIT:count will work or not in production or UAT because i was going through salesforce documentation which according to me states that Limits.getLimitQueryRows()=50000 and Limits.getQueryRows()=number of query returned. – vineet Jun 5 '17 at 9:11
  • @vineet This will work. Since max no of rows retrieved by soql is 50000 this is the way we avoid exceptions. The count specifies no of rows you can retrieve in this transaction. – Reshma Jun 5 '17 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.