Querying only the first record in a relationship where the relationship can have multiple records

soql

Lets take the example of the standard objects CollaborationGroup(CG) and CollaborationGroupFeed(CGF). A single CG record can have multiple related CGF records. If I have 10 CG records I want to get only 1 related CGF record for each CG record sorted by CreatedDate (descending) so that finally I will have only 10 CGF records.

So, for example, if there are 3 CGF records CGF1, CGF2 & CGF3 (written in descending order (by createddate)) for a single CG record CG1. I only want to get CGF1 as the result of my SOQL query.

Best Answer

I am not aware of object Collaboration Group hence taking example of other standard relationship to query only 1 record.

Here in my example I have taken account, contact where Account can have multiple contacts associated but we will only query 1 using below query

SELECT Id,(SELECT Id,Name,CreatedDate FROM CONTACTS order by createdDate DESC LIMIT 1 ) FROM Account

Inner query will only output one contact for each account.