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

  • 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, 2017 at 7:35

2 Answers 2


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]) {

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

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 .