Why does the following work?

List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 3];

List<Contact> contacts = [SELECT Id 
                     FROM Contact
                     WHERE AccountId = :accounts];


First, this is working on a "list of ids" (not really, it's a list of sObjects, more on that in a second) without using the IN operator (i.e AccountId IN [...]).

Second, the list is not a list of ids, but rather a list of sObjects. How does SOQL know to pull the Id of the sObject?

I someone can point me to where this is documented, that'd be great.


It is interesting that the documentation that I've found doesn't explicitly state this scenario is covered, at least in the main text, where it says:

The value of the IN or NOT IN operator in WHERE clauses, allowing filtering on a dynamic set of values. Note that this is of particular use with a list of IDs or Strings, though it works with lists of any type

That page's code example does, however, include the following comment:

// An IN-bind with an Id list. Note that a list of sObjects
// can also be used--the Ids of the objects are used for
// the bind

Suffice to say, SOQL from Apex is smart enough to convert your list of SObjects into a list of IDs for the execution of the query.

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.