I am trying to execute a block of code using the Execute Anonymous Window that is meant to delete some duplicated data, but I am getting this weird error about a variable not existing even though my debugging says otherwise.

Here is what I have:

List<AggregateResult> ars = [SELECT YTPQuiz__c quiz FROM YTPQuestion__c GROUP BY YTPQuiz__c HAVING Count(Id) > 1];
for (AggregateResult ar : ars) {

In the for-loop you will see I simply print the quiz variable I assigned during the SOQL statement, but I get an error saying that this variable does not exist.

If I replace this debug line with System.debug(ar) the log print out a bunch of object like:


Yet, I can't access the quiz variable.

If I don't alias YTPQuiz__c as quiz then it will print out


Yet, I get the error that ar.YTPQuiz__c variable doesn't exist. I even tried ar.expr0 and it said that variable doesn't exist.

I've done this exact same method of accessing AggregateResults in APEX classes and it works perfectly fine, but not this Anonymous Execution Window... What could possibly be wrong?

  • As far as I know you will need to use ar.get('quiz') to be able to get the data here. If you don't have aliases, then you use ar.get('expr0') and so on depending on the order of the field.
    – Jayant Das
    Commented Apr 23, 2019 at 23:20

2 Answers 2


You will need to utilize ar.get('alias-name') here based on the Working with SOQL Aggregate Functions documentation.

So in your case it will be:


If you didn't have any aliasing, then you would have to use expri depending on the appearance of the field in the query.

The key is not forgetting to use single quotes around your variable since it's actually a String: ar.get('quiz'), ar.get('expr0'), ar.get('YTPQuiz__c'). Forgetting them will result in a 'variable does not exist' error.


If you alias the field, you then call .get('alias'). In your case, you would do something like:

for (AggregateResult aggregate : [
    SELECT YTPQuiz__c quiz FROM YTPQuestion__c
    GROUP BY YTPQuiz__c HAVING Count(Id) > 1
    Id quizId = (Id)aggregate.get('quiz');

You must log in to answer this question.

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