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
Shruthi GM 4Shruthi GM 4 

how to write query inside a query?

I want to get the contacts related to a particular account.So how I write a query for that?
List <Contact> contacts= [Select Name,Id from Contact where (What needs to be written here?)];


Please help.
Thanks inadvance.
Richard Jimenez 9Richard Jimenez 9
Hi Shrunthi,

Id accId = '001b000003KenKW';
List <Contact> contacts = [SELECT Id, Name FROM Contact WHERE AccountId = :accId];

Thanks,
Richard.
BALAJI CHBALAJI CH
Hi Shruthi,

If you want to get contacts related to particular account, you can query using Account ID.
List <Contact> contacts= [Select Name,Id from Contact where AccountID=:AccId];
Here, AccId is the ID of the Account whose contacts can be retrieved.

For Nested Query Example:
List <Account> contacts= [Select Name, Id, (Select id, name from contacts) from Account];


To use Nested queries, please find below links.
http://blog.jeffdouglas.com/2010/02/22/soql-how-i-query-with-thee-let-me-count-the-ways/
https://developer.salesforce.com/page/A_Deeper_look_at_SOQL_and_Relationship_Queries_on_Force.com
https://developer.salesforce.com/forums/?id=906F00000009398IAA

I would like to know if that helps you.

Best Regards,
BALAJI



 
Amit Chaudhary 8Amit Chaudhary 8
Hi Shruthi GM 4,

Please check below post for SOQL
1) https://developer.salesforce.com/page/A_Deeper_look_at_SOQL_and_Relationship_Queries_on_Force.com
2) https://developer.salesforce.com/page/From_SQL_to_SOQL

Please try below code.
Option 1:-
List <Account> listAccount = [Select Name, Id, (Select id, LastName from contacts) from Account];
For(Account acc: listAccount )
{
 System.debug('--------Account-------->'+acc.Name);
 List<Contact> listConts = acc.contacts;
 For(Contact cont : listConts )
 {
    System.debug('----Contact--->'+Cont.LastName);
 }
}
Option 2:-
List <Contact> contacts= [Select Name,Id from Contact where Accountid in (select id from Account )];

System.debug('----------------->'+contacts.size());

Let us know if this will help you