+ Start a Discussion
SV MSV M 

How to query specific number of Contacts related to Account

Hi,

I have a requirement where I need to display only 2 Contacts related to each Account in a list view. Can someone help me how to build the query for my requirement...

Thanks in Advance...
RituSharmaRituSharma
Use limit word. Your SOQL would be something like:

Select Id,Name,(Select Id from Contact limit 2) from Account

You may need to add necessary fields and filters as per your need.
SV MSV M
Hi RituSharma,

The query you gave was throwing an error says "Didn't understand relation between Account and Contact". Tried solving it but no luck. Can you help me on this...
RituSharmaRituSharma
There was a typo error....Try below query:

Select Id,Name,(Select Id from Contacts limit 2) from Account
RituSharmaRituSharma
Please mark my answer as the best answer if the query worked for you. This would help others in future.
SV MSV M
While running the query I was getting an error says Illegal assignment from List<Account> to List<Contact>. Can you help me how to solve this...
RituSharmaRituSharma
Query that I shared will retrun list of accounts and it it seems that you are trying to assign to list of contacts. It should be like below:

List<Account> accountList = [Select Id,Name,(Select Id from Contacts limit 2) from Account];