I have a sObject List AttachList

        Boolean retVal = false; 
        DateTime AttachCreatedDate = '';
        ID attachId = '';

        for(AttachDetails__c attachDetail : AttachList) {
            if(attachDetail .CreatedDate>AttachCreatedDate){
                AttachCreatedDate =attachDetail .CreatedDate;
                attachId =attachDetail .ID;

What I am trying to do here is to find the id of the record having the latest createddate. But the AttachCreatedDate field is not taking null as the initial value. can anyone offer me suggestions as to how to fix this. Is there any alternative way to find the ID of the Latest Created record


I might rename attacheCreatedDate to mostRecent. Regardless, the simplest change is probably to instantiate it to the first value in the list:

Datetime mostRecent = attachList[0].CreatedDate;

Not sure how you ever got this line to compile, but it should replace:

Datetime AttachCreatedDate = '';
  • Id attachId = '' is also invalid (compiles but will crash at the point of assignment). – sfdcfox May 18 '16 at 5:00
  • I should have figured that out. Thanks @Adrian. It was super helpful – Rimii May 18 '16 at 5:44

If you don't mind burning a query, for example, when it's just once per transaction on a Visualforce page, you can just ask the database:

Id attachId = [SELECT Id FROM AttachDetails__c WHERE Id IN :attachList ORDER BY CreatedDate DESC LIMIT 1].Id;

Do make sure that attachList is not empty first, or you'll get a no-rows-for-assignment exception.

Alternatively, you could also choose to compare to null first:

for(AttachDetails__c attachDetail : AttachList) {
  if(attachCreatedDate==null || attachDetail.CreatedDate>AttachCreatedDate) {
    AttachCreatedDate =attachDetail.CreatedDate;
    attachId =attachDetail.ID;

But this is slightly less efficient than setting the attachCreatedDate variable to some already known value.

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.