function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
vhanson222vhanson222 

SOQL Relationship query question

Is it possible to limit a query to only return records with subrecords?  For example, I want to find all Accounts that have at least one Note record associated with them.

 

IE:

List<Account> accountsWithContacts = [SELECT Name, Id, (SELECT Id FROM Notes) FROM Account WHERE Notes.size > 1];

 obviously the above example code is invalid, but essentially that is what I would like to accomplish.

 

any advice is greatly appreciated -- this seems like something that should be able to be accomplished via SOQL instead of having to return all accounts and sort them out after the query.

Best Answer chosen by Admin (Salesforce Developers) 
Starz26Starz26

Something like this?

 

Account[] a = [Select ID, Name, (Select ID From Contacts) From Account where ID IN (Select AccountID From Contact)];

All Answers

Starz26Starz26

Something like this?

 

Account[] a = [Select ID, Name, (Select ID From Contacts) From Account where ID IN (Select AccountID From Contact)];

This was selected as the best answer
vhanson222vhanson222

That did the trick.  Thanks!