Order By Examples

AVAILABLE API VERSION
API v59.0 and later

You can use aggregate functions with or without an orderBy argument.

This example queries the Industry field and an aggregate count function on Name, grouped by Industry. Use the orderBy argument for the aggregated Name field.

The result lists all industries and the number of accounts that are assigned to that particular industry.

By default, null values are returned first the results. To remove accounts without a specified industry, use where: { Industry: { ne: null } }.

All aggregate functions ignore null values, except for COUNT() and COUNT(Id).

The previous query is similar to this SOQL statement.

Similar to SOQL, you can't order by the aggregated name count unless you also group by Industry. For example, you get an error if you don't provide GROUP BY Industry.

You also can't group by the aggregated name count. Only date aggregate functions are allowed in a grouping.

This example queries the Industry field with 2 aggregate functions on AnnualRevenue and Name fields. Use the orderBy argument for the aggregated fields.

The result lists all industries, the corresponding average amount on the AnnualRevenue fields, and the number of accounts that are assigned to that particular industry.

The previous query is similar to this SOQL statement.

To return the minimum value of a field, use the min function. This example returns the minimum value of the AnnualRevenue field for each industry.

The orderBy argument orders the results in ascending order of annual revenue. Similar to SOQL, you can't order by the aggregated minimum annual revenue unless you also group by Industry. In other words, if you use orderBy in a query, you must also include the groupBy argument.

The previous query is similar to this SOQL statement.

SOQL and SOSL Reference: ORDER BY