Activity Forums Salesforce® Discussions SOQL Query ( Accounts and Contacts ) in Salesforce Reply To: SOQL Query ( Accounts and Contacts ) in Salesforce

  • Shaharyar

    Member
    August 10, 2017 at 5:12 am

    Hello Rahul,

    #Apex Class

    public class AccountAndContacts {

    public static void displayContacts(){
    List<Account> acc=[Select Id,Name from Account];
    for(Account a:acc){
    List<Contact> con=[Select LastName from contact where AccountId=:a.id];
    for(Contact c:con){
    if(con.size()>1){
    System.debug('AccountName '+''+a.Name+'RelatedContacts '+''+c.LastName);
    }}}}}

     

     

    #Anonymous Window

    AccountAndContacts.displayContacts();

     

    #Check the output in debugger log...

    Hope it will help you.

    Note:I have written it in simple understandable ,way you can optimize code by using nested query.