SOQL to retrieve all contacts for an Account (related and direct)

After clarifying in a comment on your question, we're working with the Associate Contacts with Multiple Accounts feature, which was made generally available in Summer '16 (API v37.0)

After you've enabled Contacts to be related to multiple Accounts, if you wish to retrieve all the related contacts on an Account, you'll need to query the AccountContactRelation object, which is the junction object Salesforce is using to track the Many-to-Many relationship.

The following queries should work

Using a semi-join:

SELECT Id, Name FROM Contact WHERE Id IN (SELECT ContactId FROM AccountContactRelation WHERE AccountId = <account Id here>)

Using a parent-child subquery

SELECT Id, (SELECT Contact.Name FROM AccountContactRelations) FROM Account WHERE Id = <account Id here>)

The different results that you're getting between the dev console and compiled Apex may be due to your Apex using an API version of 36.0 or below.


If your AccountId is actually populated with the Id of the Account record, you should get a return value from:

SELECT Name Contact WHERE AccountId = '<valid_id>'

Note that it is preferable to use AccountId over Account.Id.

You also don't need to filter your subquery if you go that route. Again, if the lookup is populated, you should see results:

SELECT (SELECT Name FROM Contacts) FROM Account WHERE Id = '<valid_id>'

If you are not seeing results, it is possible that you are running into a permissions issue. That is unlikely, however, since you seem to have record visibility based on your unfiltered query.

It is unclear based on your post what you mean by "direct" versus "related" Contact records, but if by "related" you mean something other than "related via Lookup" the relationship will not be populated and you will need to go a different route.

Tags:

Soql

Apex