I have a scenario as below

Account --> contact (multiple)

Multiple contacts can be related to an account and I want to get only the contacts where there is a field called industry != a specific criteria.

eg: How do I group all the contacts that are related to an account where the contact's industry != 'Electronics' and this needs to be displayed on a visual force page. I think I need to create a map of account, contacts_with_industry!='Electronics' and use this map in VF, but the problem is map does not accept duplicate key (account Id)

How do i get only those contacts related to the account where it does not meet a specific criteria

Thanks in advance for the help

  • 1
    Can you add to your question and include some code which you've attempted to use to solve this problem? – Mark Pond Apr 18 '13 at 16:51
  • did the answer help you or can you provide more context to help us answer your question? – Mark Pond Apr 22 '13 at 3:55

To answer this question specifically:

How do i get only those contacts related to the account where it does not meet a specific criteria

It can be done a couple of ways depending on how you wish to work with the results. If you just need a list of Contacts with data on each Contact about their related Account:

List<Contact> contacts = [SELECT Id
                                , FirstName
                                , LastName
                                , Industry__c
                                , AccountId
                                , Account.Name                              
                            FROM Contact
                            WHERE Industry__c != 'Electronics'];

If you want a list of Accounts with a list of Contacts under each one you can use a subquery:

List<Account> accounts = [SELECT Id
                                , Name
                                , (SELECT Id
                                        , FirstName
                                        , LastName
                                        , Industry__c                                                                   
                                    FROM Contacts
                                    WHERE Industry__c != 'Electronics')
                            FROM Account
                            LIMIT 5];

Each account in the list will have child list identified as Contacts. The nested list can be accessed in a variety of ways.


for (Account a : accounts) {
    for (Contact c : a.Contacts) {

Similar markup in VisualForce:

<apex:repeat value="{!accounts}" var="a">
    <apex:repeat value="{!a.Contacts}" var="c">
        <apex:outputText value="{!c.FirstName}" />

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.