Search code examples
mysqlsqlprimary-keyuniqueidentifier

How to to create unique random integer ID for primary key for table?


I was wondering if anybody knew a good way to create a unique random integer id for a primary key for a table. I'm using MySQL. The value has to be integer.


Solution

  • If your're open to suggestions and you can implement it, use UUIDs. MySQL's UUID() function will return a 36 chars value which can be used for ID.

    If you want to use integer, still, I think you need to create a function getRandID() that you will use in the INSERT statement. This function needs to use random + check of existing ids to return one that is not used before.

    Check RAND() function for MySQL.