I know this might be a very basic question but i'm pretty confused by this:

Map<Id,Account> accountWithOpportunities = 
    new Map<Id,Account>([SELECT Id,(SELECT Id FROM Opportunities) FROM Account]);

I have no clue on to where the Opportunities are relevant at all in this map and how they are stored or can be accessed?

Can anyone clear this out for me?

2 Answers 2


They're stored in a List<Opportunity> variable on each Account in the Map<Id, Account> you're getting back from the constructor.

You'd access them like this (using a for loop as an example):

for (Opportunity o : accountWithOpportunities.get(accountId).Opportunities) {
     // Do stuff

Here's a reference in the Apex Developer Guide.


You can access Account and it's related Opportunities

for(Account acc : accountWithOpportunities.values()){
    //Related Opps
    for(Opportunity opp : acc.Opportunities){
  • This answer isn't really different than that which is already accepted.
    – Adrian Larson
    Mar 6, 2018 at 21:47

You must log in to answer this question.

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