SOQL GROUP BY Clause: COUNT, HAVING, ROLLUP and Apex Examples (Tested)

SOQL GROUP BY returns one row per distinct value of a field, with an aggregate such as COUNT(Id) or SUM(Amount) beside each value. The clause order is fixed:

SELECT GroupField, AGGREGATE(Field) alias
FROM ObjectName
WHERE row_filter
GROUP BY GroupField
HAVING aggregate_filter
ORDER BY AGGREGATE(Field) DESC
LIMIT n

It runs anywhere SOQL runs: the Developer Console Query Editor, inline Apex, the sf CLI and the REST and SOAP APIs. Every query below ran in our Winter ’27 Developer Edition org on November 18, 2026, so you can copy one, swap the object and field, and read the result the same way.

This Tutorial Covers: