Search code examples
salesforceapex-codesoql

Is there a way to group by the date portion of a datetime field in SOQL?


Is there a way (without creating a formula datevalue(datetime) field) to aggregate a SOQL query on the date portion of a datetime field? For example, I'd like to do something like:

select datevalue(datetimeField), count(Id) from object__c group by datevalue(datetimeField)


Solution

  • While you can't group on a datetime field directly, there are a number of date/time functions for aggregates, so that you can group by part of the dateTime value. For example here's a query that'll show the number of account records created on each date.

    select day_only(createdDate) createdonDate, 
        count(createdDate) numCreated 
        from account 
        group by day_only(createdDate) 
        order by day_only(createdDate) desc
    

    The docs have details of all the date functions for aggregates.

    day_only() returns the date part of a dateTime field.