Grouping Records

SOQL provides the GROUP BY syntax for grouping records by one or more fields. When a query contains a grouping, its results are collapsed into a single record for each unique value in the grouped field. Because you can no longer return individual field values, all fields not specified as grouped must be placed within aggregate functions.

Listing 5.3 shows a simple example of grouping records without aggregate functions. It examines all the records in the Contact object and returns only the unique values of the field Region__c.

Listing 5.3 Returning Unique Records by Grouping Them

for (AggregateResult r : [ SELECT Region__c FROM Contact  GROUP BY Region__c ]) {  System.debug(r.get('Region__c')); ...

Get Development with the Force.com Platform: Building Business Applications in the Cloud, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.