SOQL return types

When used in Apex code, a SOQL query can return three type of result: a list of sObjects, a single sObject, or of Aggregate Results.

SOQL query that return a List<sObject>

We have already seen this:

List<Contact> conList = [SELECT Id, Name FROM Contact];

SOQL query that return a Single sObject

If only 1 row is returned, it can be assigned to a single Object as well.

Contact conObj = [SELECT Id,Name FROM Contact limit 1];

In this case, if the query does not return any rows, a runtime error will be thrown as nothing can be assigned to conObj.

SOQL query that return a List<AggregateResult>

For all group by clauses, an aggregate result is returned in APEX: This can be iterated to find individual values using the get function.

List<AggregateResult> apts = [SELECT Count(Id) nbrOfAppointments, clinic__c
  FROM Appointment__c];
for(AggregateResult ar: apts){
  system.debug('clinic:'+ ar.get(clinic__c));
  system.debug('count:'+ ar.get(nbrOfAppointments));
}

Note that field aliasing is used for count(Id) nbrOfAppointments. Aliasing is only supported for aggregate functions inside Group By clause.