I have a SObject called DDStatus__c which has LastUpdated__c field (DateTime type). How can I get latest datetime using SOQL query.

  • 2
    Per record or overall MAX as an aggregate result ? – techtrekker Jan 4 '13 at 11:17

You should be able to do this query to get the record showing the latest datetime:

[Select Id From DDStatus_c Order By LastUpdated_c DESC Limit 1]

You can add a Where clause if this is a child object and you're looking for the latest datetime for a specific parent record.

  • [Select Id From DDStatus_c Order By LastUpdated_c DESC Limit 1] is returning list. why? – Bhushan Lodha Jan 4 '13 at 18:33
  • 1
    Any SOQL query statement will return a list. But there are few exceptions like the COUNT aggregate query that returns an integer. You can get the first element from the list returned by the query by checking the list count. – Vijay Prakash Jan 5 '13 at 15:55

Unless I'm missing something, this line should work, as long as you are certain the record you're querying for exists. If you aren't sure it exists, you should cast the query to a list, and look for the first element in the list to get the field value from.

Datetime dt = [select LastUpdated__c from DDStatus__c where Id = :someId].LastUpdated__c;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.