0

This question already has an answer here:

I am quite new to SOQL so I don't know if it is even possible this way. I want to have query like this:

Account[] childrenAccs;
...
Account[] parentAccs = [SELECT Id, ParentId FROM Account WHERE Id IN :childrenAccs.ParentId];

With this query I want to get all Accounts, which have Id equal to ParentId of any Account from childrenAccs collection. Is this possible to achieve somehow? Or I have to extract ParentIds from childrenAccs and use that in the condition WHERE IN instead?

Thanks a lot for advices

marked as duplicate by martin, Raul, Ratan Paul, Mohith Shrivastava apex Feb 28 '17 at 14:21

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    It's possible, first you need to collect parent ids in a set and do a query on account matching account ids – Raul Feb 28 '17 at 7:35
1

Usually, Set or list is used against IN operator.

Try something like this:.

// Set to collect parent ids
Set<Id> setParentId = new Set<Id>();

// query on all Child Accounts, added ParentId != null for getting all child records
for(Account objAccount: [SELECT Id, ParentId, Name FROM Account
    WHERE ParentId != null]) {
    setParentId.add(objAccount.ParentId);
}

// Here you can use, ParentId IN :setParentId, in SOQL to get all parents
List<Account> lstParentAccount = [SELECT Id FROM Account WHERE 
    ParentId IN :setParentId];
1

The IN statement requires a list, and in this case, a list of Ids. You can use apex to gather the ids into a set, and then bind that variable in the query.

Account[] childrenAccs;
...
set<Id> ParentIds = new set<Id>();
for (Account a : childrenAccs) ParentIds.add(a.ParentId);
Account[] parentAccs = [SELECT Id, ParentId FROM Account WHERE Id IN :ParentIds];

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