[SalesForce] generate unique number for each record

I need to generate a unique 7 digit number for each contact record. This generated number is a "Customer Id" that makes it easy for customers to reference their account.

I have two solutions, but I don't like any of them.

  1. Sequential generation. I will count the total number of customers before insert, then just add 1 to that count. So say there are 20 customers, when the 21st gets insert, their Customer Id will be 0000021. What I don't like about this is I have to consider deleted records. This is fine if I use ALL ROWS in my query, but what if someone empties the recycling bin? This solution seems more restrictive but more scalable.

  2. Random generation. Generate a random 7 digit number string before the record gets inserted. This solution is nice because I don't need to worry about deleted records. But then I need to worry about if say we have 3 million customers, each with a unique customer id, we are increasing the chance of generating a random that is already in use. We can always try an insert again, but that doesn't appear ideal. This solution has more freedom but not as scalable.

Is there a better option that I have not considered?

Best Answer

You can also consider generating them based on a date and time. The current date will never repeat in the future, even if you delete the records. A customer created now could be number 1719071915, for example. Can you identify the mask used?

Day Year Month Minutes Hours

Pros:

  1. It is not random.
  2. It will not repeat itself.
  3. You can reverse it to get the customer's account creation date.
  4. "You can have two or more customers registrating at the same time", right? You can also add milliseconds to that mask, so I don't think this is a big issue. You can also set it to be a unique number, so if you fail to insert a record with a given number, you can always wait a few milliseconds to insert the next one.

Regarding the Autonumber field

You don't have to worry about the autonumber field, since Salesforce will manage the used numbers for you. If you create a record now, starting with 0, then another record that will have 1 as its Name, and you delete the first one, Salesforce will automatically manage things for you and set "2" for the next record. A caveat with this approach is if an administrator or developer changes the field type. This would indeed "reset" it and cause some trouble for you. But if it is a sequential number, then you can just set the "start at" parameter (which I admit not remembering the correct name right now).