Loading

Convert Apex Aggregate Query Results to String or Integer Format

Fecha de publicación: May 17, 2026
Descripción

When running SOQL (Salesforce Object Query Language) aggregate queries in Apex — such as those using COUNT(), SUM(), MIN(), MAX(), or AVG() — the results are returned as an AggregateResult object, not a directly typed numeric value. The AggregateResult.get('alias') method returns an untyped Object.
To use the numeric result in further Apex logic — such as displaying it in a message, comparing it to a threshold, or passing it to another method — it must first be cast to a String using String.valueOf(), and then optionally to an Integer using Integer.valueOf(). This article provides a sample code pattern for this two-step conversion.
Example use case: A developer needs to count the total number of Contact records created after a certain date and compare that count against a limit to determine whether to send an alert notification.
Use String.valueOf() and Integer.valueOf() to convert aggregate results to a string or integer format.

Solución

How to Convert Aggregate Results

The following Apex code demonstrates how to:

  1. Run a SOQL aggregate query to count Contact records created after a specific date
  2. Retrieve the count result from the AggregateResult object using the alias cnt
  3. Convert the result first to a String, then to an Integer for use in further processing

Code to convert

public list<AggregateResult> countContacts = new list<AggregateResult>();

countContacts = [Select count(Id)cnt from Contact where createddate>=2013-06-03T12:54:40.000Z ];  

String str = String.valueOf(countContacts[0].get('cnt')) ;
Integer I = Integer.valueOf(str) ;

system.debug('String Value - '+str);
system.debug('Integer Value - '+I);

 

Explanation of the Conversion Steps

  • countContacts[0].get('cnt'): Retrieves the value aliased as cnt from the first row of the aggregate result. The alias cnt corresponds to count(Id)cnt in the SOQL query. The return type of .get() is Object.
  • String.valueOf(countContacts[0].get('cnt')): Converts the untyped Object to a String representation of the number (e.g., "42").
  • Integer.valueOf(str): Parses the String value into an Integer (e.g., 42) that can be used in numeric comparisons or arithmetic.
This two-step conversion is necessary because Apex's AggregateResult.get() method always returns an untyped Object, and Apex does not allow direct casting from Object to Integer without going through a String intermediary.

When to Use This Pattern

Use this pattern whenever you need to:
  • Compare an aggregate count or sum to a numeric threshold
  • Pass an aggregate value to a method that expects an Integer or String parameter
  • Display an aggregate result in a text-based output (e.g., in an email, a flow screen, or a debug log)
Número del artículo de conocimiento

000386033

 
Cargando
Salesforce Help | Article