-2

I have a condition where I need to get list of Contacts based on many conditions, which I'm able to do but now I need to limit the number of Contacts per Account.

For the new scenario I need to switch back to inner queries, so for this case I need to switch to inner queries. Now when I use the inner queries for Contacts my batch size is too large, I want to limit the number of Contacts per Account without using inner queries.

SOQL Without Inner Query:

'Select Id,Name FROM Contacts WHERE '+ where_cond+ '

SOQL with Inner Query:

'SELECT Id,(Select Id,Name FROM Contacts WHERE '+ where_cond+ ' LIMIT : numberOfContacts) FROM Account'
1

You cannot modify your direct Contact query

Select Id, Name FROM Contacts WHERE '+ where_cond+ '

to select a specific number of Contacts per Account. Instead, limit your outer query with filters on the Account:

SELECT Id,
       (Select Id,Name FROM Contacts WHERE '+ where_cond+ ' LIMIT : numberOfContacts) 
FROM Account
WHERE <some condition> 

to reduce the total amount of data and total number of rows being processed to an acceptable level, or utilize an Account-centered batch class running at a lower batch size.

Alternately, postprocess your Contact query results in Apex to isolate a limited group of Contacts per Account. Adding ORDER BY AccountId, [some other field] is likely to be helpful there.

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.