Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to get the associated CaseComment's CommentBody for a list of cases.

String queryFields = 'Id, Subject, CaseComment.CommentBody';
 List<Case> cases = Database.query('select '+ queryFields +' from Case');
 for(Case c: cases){

but this doesn't work as there is no reference in Case object for the CaseComment. CaseComment has the field parentId which stores id of associated Case. How can I get CaseComment. I don't want to query the CaseComment object for each case in a loop.

share|improve this question
up vote 3 down vote accepted

You must traverse the child relationship CaseComment, for example:

List<Case> cases = [Select (Select Id, ParentId, IsPublished, CommentBody, CreatedById, CreatedDate, SystemModstamp, LastModifiedDate, LastModifiedById, IsDeleted From CaseComments) From Case ];

for(Case c : cases)
    for(CaseComment comm : c.CaseComments)

This is because there are many Case Comments to one Case, i.e. a one to many relationship between case and comment as per the master/detail or lookup relationship.

You should consider using Eclipse schema viewer so that you can find these relationships out yourself, its a simple point/click interface so you can traverse them graphically.

share|improve this answer
Thanks for you answer. I also need EmailMessage associated with case. In EmailMessage object (…) I see a ParentId field that says 'id of parent case', but in eclipse Schema viewer I don't see any child relationship for email messages – vishesh May 10 '14 at 9:48
Same deal, [select id, (select id from emailmessages) from case] but I think you have to enable 'Email To Case' in org to see the object – Phil Hawthorn May 10 '14 at 10:00
Thanks, enabling email-to-case did it for me – vishesh May 10 '14 at 10:14

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.