0

If my table requires alphanumeric random string as its primary key, how can I achieve this?

If we can only achieve this in the backend system instead of database system, how can we guarantee that the random string is unique in the table?

Would the algorithm look like this?

  1. generate a random string
  2. query the database and check if the string already exists
  3. if not exists, insert a row into the table
  4. if exists, re-generate a random string, and check again until the string is unique

I am primarily asking how to generate random strings in the DATABASE SYSTEM, not random strings in general.

Joshua Leung
  • 2,219
  • 7
  • 29
  • 52
  • 1
    Have you checked out mysql's uuid() function? – Shadow Nov 22 '15 at 02:46
  • 3
    see http://stackoverflow.com/questions/1846202/php-how-to-generate-a-random-unique-alphanumeric-string **OR** http://stackoverflow.com/questions/48124/generating-pseudorandom-alpha-numeric-strings **OR** http://stackoverflow.com/questions/2799495/generate-unique-random-alphanumeric-characters-that-are-7-characters-long **OR** ... – Sean Nov 22 '15 at 02:47
  • Random values can by definition collide. The bigger the range of characters, and the longer the string, the less likely you are to get collisions, but you would still have to check that it has not been used before, if you want to be 100% sure. A much better solution would be to use an auto-incremented value, which MySQL already gives you out of the box. It would render your problem moot. – Sverri M. Olsen Nov 22 '15 at 03:00

1 Answers1

2

Take a look at uniqid() http://php.net/manual/en/function.uniqid.php

"Gets a prefixed unique identifier based on the current time in microseconds."

Pistachio
  • 1,652
  • 1
  • 18
  • 38