1

Let's say you run a SOQL aggregate query that looks like this:

select OwnerId, sum(ExpectedRevenue)val from Opportunity GROUP BY ROLLUP(OwnerId)

For whatever reason, there are no Opportunities with ExpectedRevenue fields populated.

You get a table that looks like this:

val___|OwnerId

     |Id1
     |Id2
     |Id3

4/4 records.

(sidenote: how do you put in tabular data without it looking terrible?)

Take note that the "val" columns are all null and the last OwnerId column is also null.

There are 4 rows because SOQL returns a "total" row as well on rollups.

While looping through the AggregateResult[] that gets returned the code blows up on a line that looks like this: AggregateResult[0].get('val'); with a "System.NullPointerException: Attempt to de-reference a null object"

However, if just 1 of those users has some data, then the whole thing works. So I'm guessing that if no rows have any data in a particular column, that column does not exist at all and calls to retrieve it blow up.

So my question is how do you determine if a column exists to avoid the null reference error?

Ryan Elkins
  • 5,731
  • 13
  • 41
  • 67

2 Answers2

1

You have said that the ownerid column and the val columns are all null, therefore AggregateResult[0] is a pointer to a null object and any attempt to get a alue from that object give you the error you are having.

What I expect you want to be doing is before you run

AggregateResult[0].get('val');

you want to have an if statement say

if(AggregateResult.size() > 0)

or possibly

if(AggregateResult[0] != null)

to ensure that you are not attempting to access an empty object.

Try that and it should work. Otherwise post up a bigger code listing to look through.

Paul

pbattisson
  • 1,230
  • 2
  • 10
  • 24
0

If there is no data to summarize for the filters you specify in your where clause you'll get an empty list of AggregateResult back. You can test for this using list isEmpty() in Apex.

Ralph Callaway
  • 1,768
  • 1
  • 15
  • 34