0

For example, first I will retrive a List of A sObject:

List<A__c> A = [SELECT Id, Name FROM A__c WHERE ...];

Then I will retrieve a List of B sObject by A List like:

List<String> idList = new List<String>();
for(Integer i = 0; i < A.size()) {
    idList.add(A[i].Id);
}
List<B__c> B = [SELECT Id, Name FROM B__c WHERE A__c IN :idList];

Is there any better way to achieve this? How to avoid new a idList?

3 Answers 3

2

You don't need a separate collection (Map, List, or Set), just use the list of records directly:

List<A__c> A = [SELECT Id, Name FROM A__c WHERE ...];
List<B__c> B = [SELECT Id, Name FROM B__c WHERE A__c IN :A];

This works because an sObject list used as a binding for B__c automatically assumes you want the Id for each A__c in the list of A__c.

1
  • wow didn't know this before, used to wonder whether it can work, thank you !
    – Lanjinest
    Jan 4, 2021 at 6:00
2

Just use a semi-join:

SELECT Id, Name FROM B__c WHERE A__c IN (SELECT Id FROM A__c WHERE ...)

You can read more about this strategy in the SOQL and SOSL Reference.

3
  • Thank you bro! Is semi-join inside semi-join doable?
    – Lanjinest
    Jan 4, 2021 at 3:24
  • You cannot nest semi-joins or anti-joins, no.
    – David Reed
    Jan 4, 2021 at 3:25
  • Noted! Thank you!
    – Lanjinest
    Jan 4, 2021 at 3:27
2

You can use Map as a return type from SOQL. Documentation

Map<ID, A__c> mapOfA = new Map<ID, A__c>([SELECT Id, Name FROM A__c WHERE ...]);


List<B__c> B = [SELECT Id, Name FROM B__c WHERE A__c IN :mapOfA.keySet()];
1
  • This is also another way to try! Thank you!
    – Lanjinest
    Jan 4, 2021 at 3:28

You must log in to answer this question.

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