I love people who downvote questions without commenting what they think could be improved...
Some general reading material:
Generally speaking - you should consider the fact that optimizing this query now might backfire on you in the long run. If a "right" combination of ObjectB's is used - you'll hit the limit of 50K queried rows and your transaction will roll back. Not to mention the fact that user than manually insert a record with "popular" Contact will wait forever for simple save to finish... Couple ideas:
- cut into chunks and offload to
@future
call
- or submit a batch job that can handle such workload easier
- or reduce the "batchSize" of your import
In your case - either I'm not reading the question right or you've overly complicated it.
(SELECT Contact__c FROM ObjectB__c WHERE id IN :idList)
the idList is built off trigger.new
plus I assume it happens in trigger somethingSomething on ObjectB__c(after insert)
You already have all your ObjectB__c records in the trigger.new
. There's no need to query for them & their contacts.
So if you'll collect all Contact Ids...
Set<Id> contactIds = new Set<Id>();
for(ObjectB__c b : trigger.new){
contactIds.add(b.Contact__c);
}
contactIds.remove(null);
System.debug(contactIds);
... you'll be able to write a simplified query:
SELECT Id, Name, Contact__c
FROM ObjectA__c
WHERE Contact__c IN :contactIds
If that one will still fail on you and you can't filter them more & can't reduce the batch size - yep, asynchronous processing time (@future or batch job).