I have been using the below SOQL to get the Notes and Attachments that have been added to a record in my Custom Object Request_For_System_Change (alongside all the other fields I need, the below is shortened)

SELECT Request_Title__c,Variable_information_required_in_extract__c
, recordType.name, Name 
, (SELECT Id, Name, ContentType, OwnerId, CreatedDate  FROM Attachments) 
, (SELECT Id, Title, CreatedDate, createdbyid, body FROM Notes)      
FROM Request_for_System_Change__c where Id = :recordId ];   

Then I have been using two tables in my VF page to display the Notes and Attachments as below:

enter image description here

Now my manager has pointed out that in order to see the history really we need all the attachments and notes together in one table in descending date order like they are in the standard SalesForce page:

enter image description here

So how could I get all those records together in one SOQL query which I can then in one table?

1 Answer 1


I'm presume the issue that you're running into is that you can't use an OrderBy clause in a SubQuery, so you're looking for a way to sort the results. That's something you'll need to do manually in a for loop once the results have been returned.

This will be easiest if you first cast the Note Object and the Attachment object records to a common Type so you can put them into a combined list of records for sorting by date then extract them later.

I don't have time to explain casting at the moment, but you'd want to use casting along with the comparable interface to do your sorting.

  • Thanks for this can you give me some guidance on what common type to cast to? Commented Jan 21, 2016 at 17:41
  • 1
    I'd think you'd want to create a wrapper class of some kind. See the example in the comparable I pointed you to.
    – crmprogdev
    Commented Jan 22, 2016 at 4:40

You must log in to answer this question.

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