I'm operating within the context of a before insert operation, but I'd like to display the current auto number on the creation page. Without the record being inserted into the database it isn't possible to display the number.

I thought of doing something like this in apex (pseudo-code):

Integer LastNumber = [SELECT Name FROM Object ORDER BY CreatedDate] // Get the last record
LastNumber = stripAutoNumberPrefix(LastNumber); // Strip the prefix 
return LastNumber + 1; // Increment one to the number and you have the new auto number.

to get the next autonumber in sequence, as there's no system methods I can use.

Is this a good idea? Is the order of auto-numbers explicitly guaranteed?

  • 4
    Auto number sequence is not guaranteed to be the last visible +1. Several thing could expose a gap including visibility, test methods, database events for example
    – Eric
    Apr 25, 2017 at 15:20
  • Could you explain better why you need it? It is not making sense for me.
    – m Peixoto
    Apr 25, 2017 at 16:40
  • Unit tests also increment auto-number values unless you explicitly specify for them not to do so: releasenotes.docs.salesforce.com/en-us/spring14/release-notes/…
    – Mark Pond
    Apr 26, 2017 at 0:42

1 Answer 1


It's a bit of a hack, but you could insert a record and immediately roll it back. That would give you the most recent auto-number, and you could increment it by 1 to figure out what the next probable number is. But like others have said, it's not guaranteed - for example, somebody else in the system could create a new record before the current user does, unit tests could run that insert these records, etc. Even the act of inserting a record and immediately rolling it back will cause the auto-number to increment (so therefore there will be at least one number separating any records created from this page).

CustomObject__c obj = new CustomObject__c();
Savepoint sp = Database.setSavepoint();
insert obj;
obj = [SELECT Name FROM CustomObject__c WHERE Id = :obj.Id];
System.debug(obj.Name); // This will be the current auto-number - increment it by one

So, that's a solution you may be able to try if it's absolutely necessary to show the next probable number. I honestly wouldn't recommend it though, for the reasons stated above.

  • 5
    Edited to highlight that even the rollback will cause the outnumber to increment
    – Eric
    Apr 26, 2017 at 0:27

You must log in to answer this question.