1

How do I pull in the accounts, with the collection of contacts where the # of contacts are greater than 0?

SELECT account.id, account.name, (
                                   SELECT contact.firstName, contact.lastName 
                                   FROM account.contacts WHERE **count > 0** 
                                    ) 
FROM account LIMIT 100

3 Answers 3

0

Phil's solution will work great if you just care about returning accounts that have contacts, just bear in mind you'll get multiple rows for accounts with more than one contact.

If you want an arbitrary number, i.e. 2, you'd need to first query the accounts meeting that criteria than the contacts.

// grab ids of accounts having 2 or more contacts
Set<Id> accountIds = new Set<Id>();
for(AggregateResult agg : [
    SELECT COUNT(Id), AccountId FROM Contact
    GROUP BY AccountId HAVING COUNT(ID) >= 2
]) {
    accountIds.add((Id) agg.get('AccountId'));
}
// query the contacts
List<Contact> contacts = [
    SELECT Account.Name, FirstName, LastName 
    FROM Contact WHERE AccountId in :accountIds
];
2
  • 1
    If you alias accountid as Id, case sensitive, you can make a map of id to aggregateresult. This saves the loop afterwards.
    – sfdcfox
    Jun 18, 2014 at 1:34
  • @sfdcfox that is an awesome tip, did not know you could do that Jun 19, 2014 at 1:44
2

Another way to do what you want is to query Contact rather than Account, and pull in the fields you want from Account, for example:

Select AccountId, Account.Name, FirstName, LastName From Contact;

You'll only get Accounts where there are Contacts because of the nature of the relationship (i.e. Account being the Parent of Child).

If you wanted to prevent Contacts been selected without an Account, you could add a where clause of AccountId != null.

I don't think you can do it (with just one SOQL) the way you have expressed it.

2
  • Ok, switch the relationship, got it. So the context of this is I'm reading up on Parent-Child relationships and trying to come up with some good use cases. can you give me some examples? Jun 17, 2014 at 19:42
  • CAn I give you some examples of what? Jun 17, 2014 at 19:48
0

if you want to get Accounts that have at least 1 Contact (and all such Contacts for that Account)

select id, name, (select firstname, lastname from Contacts) 
   from Account where
       id IN (select accountId from Contacts)

Choose @Ralph solution if you need exactly Accounts with exactly n Contacts.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .