Skip to content Skip to sidebar Skip to footer

Random String Unique In Database Table

I need to generate a random string (8 digit alphanumeric code) and save it with my Tournament row into a database. Problem is that this code needs to be unique in the whole table a

Solution 1:

The answer is to use a unique identifier that combines a "unique" part and a "random" part.

  • The "unique" part can be a monotonically increasing counter (such as the record or row number in a database), or it can be a number generated with a full-period linear congruential generator (which cycles pseudorandomly through all possible values in its period before repeating).
  • The "random" part is simply a random number generated with a cryptographic random number generator (which Node.js has; check the documentation). In general, the longer it is, the less predictable it will be.

Moreover, for the purposes of generating unique identifiers, there is little reason to limit yourself to 8-character alphanumeric identifiers as you're now doing.

Even if you expect end users to enter a "random" and "unique" ID at some point, there are techniques you can use to ease the task of entering IDs much longer than 8 characters; they include—

  • adding a "checksum" character to the ID,
  • dividing the ID into hyphen-separated chunks, and
  • employing a system similar to Bitcoin's BIP39, in which each ID is convertible to a sequence of memorable words.

Post a Comment for "Random String Unique In Database Table"