0

Can someone tell me a good method for automatically placing a unique random number in a mysql database table when a new record is created.

vicky
  • 27
  • 2
  • 7

3 Answers3

1

I would create a table with a pool of numbers:

Create Table pool (number int PRIMARY KEY AUTO_INCREMENT);
Insert Into pool (),(),(),(),(),(),(),(),…;

And then define a trigger which picks one random number from that pool:

CREATE TRIGGER pickrand BEFORE INSERT ON mytable 
FOR EACH ROW BEGIN
  DECLARE nr int;
  SET nr = (SELECT number FROM pool order by rand() limit 1);
  DELETE FROM pool WHERE number = nr;
  SET NEW.nr = nr;
END

In order to avoid concurrency issues you have to run queries in transactions. If performance becomes an issue (because of the slow order by rand()) you can change the way to select a random record.

Community
  • 1
  • 1
Markus Malkusch
  • 7,738
  • 2
  • 38
  • 67
0

Your best option is Autoincrement Column

see here for syntax

perhaps for Random number try this!

select FLOOR(RAND() * 401) + 100

edit

SELECT FLOOR(RAND() * 99999) AS sup_rand
FROM table
WHERE "sup_rand" NOT IN (SELECT sup_rand FROM table)
LIMIT 1

Steps:

1.Generate a random number
2.Check if its already present
3.if not continue use the number
4.Repeat
vhadalgi
  • 7,027
  • 6
  • 38
  • 67
0

Your criteria of unique and random are generally conflicting. You can easily accomplish one or the other, but both is difficult, and would require evaluating every row when testing a new potential number to insert.

The best method that meets your criteria is to generate a UUID with the UUID function.

The better choice would be to re-evaluate your design and remove one of the (unique, random) criteria.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • `UUID` function will not return number? and random string in quite big – Girish May 20 '14 at 05:37
  • Because it is difficult to efficiently generate a unique random number. You haven't specified how big you want it to be. What happens when there are that many results? – Jonathon Reinhart May 20 '14 at 05:38