Joshua Leung
Joshua Leung

Reputation: 2399

how to generate random string for primary key in database table

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.

Upvotes: 0

Views: 3079

Answers (1)

Pistachio
Pistachio

Reputation: 1652

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."

Upvotes: 2

Related Questions