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

My query:

    List<Opportunity> opps = [SELECT id, Probability, LastModifiedDate, OwnerId,
            (SELECT StageName,Probability,SystemModstamp FROM OpportunityHistories order by SystemModstamp desc) 
            FROM Opportunity 
            where LastModifiedDate = LAST_N_DAYS:7];

Then I do:

    for (Opportunity opp:opps) {
        List<OpportunityHistory> histories = opp.OpportunityHistory__r;
                    // ...
                    // ...

This gives me:

Save error: Invalid field OpportunityHistory__r for SObject Opportunity

How do I access the OpportunitiyHsitory objects?

share|improve this question
up vote 5 down vote accepted

If you are accessing OpportunityHistories as a sub-query in SOQL, you would also access in the same way in Apex, e.g.

List<OpportunityHistory> histories = opp.OpportunityHistories 

The __r suffix is for custom object relationships only.

share|improve this answer

Use the relationship name, in case of OpportunityHistory this isn't with __r because it is a default salesforce object, in your case this will be

or (Opportunity opp:opps) {
        List<OpportunityHistory> histories = opp.OpportunityHistories;
                    // ...
                    // ...

If you want to find out the name of the relationship, you can perfectly find it by going to the salesforce.schema file in IDE, go to (in this case) Opportunity, Child Relationships, OpportunityHistory, there you'll find the relationshipname


share|improve this answer

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.