A curious issue was brought up in the Salesforce IRC channel this week regarding Salesforce’s “Auto-number” field type. What is this field type? When I don’t care about the name of a record, I choose “Auto-number”, and it just uses an increment-by-one number for the record name. You might think this would be a number that reliably counts the number of records for this object, right? Well, no, not at all. I did a bit of research and I found some information that other Salesforce users might find curious about this field.
The behavior of the Auto-number field type that first surprised me stemmed from running unit tests. Suppose you have an object with an Auto-number name field with a value of ‘A-0012’. Did you know that if you run a unit test that inserts 5 of these records, the next time you create a record in the org as a normal user, the Auto-number field’s value will be ‘A-0017’?
Why is this? What happened to records A-0013 through A-0016? Expected behavior is that any changes made by a Salesforce unit test are rolled back, not persisted. What is unexpected, however, is that automatic counter is not also rolled back.
Why is this? User ‘werewolf’ has shared some information on this Developer Forums post. It appears that each time an Auto-number field is created, the Salesforce platform will create a number incrementor for this field. When a number is requested from this incrementor, the system doesn’t know if the requesting record will be committed or not, so it can’t roll back its incrementor, as this breaks the field’s uniqueness by giving away the same number again.
However, this behavior seems to be fixed, according to user ‘SetupForce’ in this Developer Forums post. To opt-in to this new functionality, you have to call Salesforce Support and tell them to ensure your Auto-number fields aren’t incremented by unit tests. I am guessing that this is because it changes the original functionality of this field, and Salesforce engineers just decided it is best to ask users to manually opt-in for this functionality.
Interesting details behind this Auto-number type field, for sure. Hopefully this post will serve as an anecdote when you encounter this behavior in the future and consider it strange. And, if this behavior is a solution roadblock, recourse lies in a simple call to Salesforce Support. Happy coding!