The following SOQL gives Account.Name perfectly in workbench:

SELECT Id, Name, Account.Name FROM Opportunity

The same when used inside Apex:

for (Opportunity relatedOpp : [SELECT Id, Name, Account.Name FROM Opportunity]) {
            //gives a NullPointerExp as the Account object is NULL

How do I alter the SOQL so as to get the Account Name in Apex?

3 Answers 3


Accessing relatedOpp.Account would work fine when a Opportunity is linked to an Account and would give a null pointer exception when AccountId is null.

When accessing reference field in apex, always a best practice to perform a null check. Example below:

for (Opportunity relatedOpp : [SELECT Id, Name, Account.Name FROM Opportunity]) {
    if(relatedOpp.AccountId != null) {
        // System.debug(relatedOpp.Account.Name);

You can even optimize your SOQL to filter opportunities have AccountId populated within query itself to avoid getting all records. Its a best practice that always put WHERE condition in your SOQL statements.

for(Opportunity relatedOpp :[SELECT Id, Name, Account.Name FROM Opportunity WHERE AccountId != NULL]){

Or where there is no contact role in an opportunity. I've also added a filter to a specific account Id.

SELECT Id, Name, account.name, (SELECT Contact.Name,Contact.Email, ContactId FROM OpportunityContactRoles) FROM Opportunity WHERE accountid='0018E00000VmZfDQAV' AND ContactId != NULL

You must log in to answer this question.

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