1

I would like to write a soql query to get the first contact showed in a related list. How can i accomplish this?

1 Answer 1

5

You can use the following apex to get the first contact:

Account a = [Select Id, (Select Id From Contacts Limit 1) From Account Where Id = 'XXX'];
Contact c = a.Contacts[0];

But normally you can set the Sort By: parameter by yourself for the related list on the objects standard page. Then you must also use the same sorting in the SOQL query. For example if the related list is sorted by Name Ascending you need to modify the query:

Account a = [Select Id, (Select Id From Contacts Order By Name ASC Limit 1) 
             From Account Where Id = 'XXX'];

Or query the target object directly:

Select Id From Contact Where AccountId = 'XXX' Order By Name ASC Limit 1

You must log in to answer this question.

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