2

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

Venkatsforce
  • 727
  • 2
  • 15
  • 27

3 Answers3

4

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.

Matt Lacey
  • 25,618
  • 7
  • 66
  • 149
  • 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? – Richard Durrant Feb 18 '14 at 09: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 Feb 18 '14 at 21:21
2

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.)

Matt and Neil
  • 32,894
  • 7
  • 105
  • 186
1

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.

Keith C
  • 135,775
  • 26
  • 201
  • 437