The Custom_Object__c having the more number of records in that object how to find out the last record using apex class?

3 Answers 3


If you want to find the latest record just run a query ordered by created date:

Custom_Object__c co = [select Id from Custom_Object__c order by CreatedDate desc limit 1];

If you want the last record that was modified use LastModifiedDate instead.

  • 1
    Just wondering if this works if records have been added by inserting a list - don't all records in the list have the same createdDate value? Commented Feb 18, 2014 at 9:29
  • 1
    That's a good point. They most likely do, but in that case the best bet would be to use an autonumber field and order by that as well as created date.
    – Matt Lacey
    Commented Feb 18, 2014 at 21:21

Normally this is solved with an Auto Number field. But you don't always want to modify the schema.

By itself, CreatedDate isn't granular enough to be an authority on the last inserted record. This is because records inserted during the same second will be jumbled in your sort.

Similarly, Id is not suitable for spotting last insert, because the sort index actually includes the 3-character case-insensitivity suffix.

You can use both in combination: ORDER BY CreatedDate, Id

Here, the primary CreatedDate sort takes care of most records except those inserted during the same second, then the secondary Id sort takes over for those inserted during the same second.

(Note: if Salesforce unlocked audit field values) an existing AutoNumber is the only ultimate authority.)


An auto-number field, added explicitly for this purpose or it could be the name field if that is an auto-number field, plus the desc limit 1 avoids the problems of using date fields. See the related question How to query records by insertion order in SOQL?`for some more background.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .