Home > Uncategorized > MySQL and Random

MySQL and Random

Yesterday, when writing some tests involving data stored in MySQL, I was quite impressed to discover that I could add random data to the table by doing:

UPDATE table SET column = FLOOR(8 * RAND()) + 1;

I was originally worried that this would pick a random value and then assign it to every row, but no, it picks a new random number each time.

Of course, I shouldn’t have been quite so surprised as I’ve long been a fan of picking a random row via:

SELECT * FROM table ORDER BY RAND() LIMIT 1

I’d just never thought through the implication that this must indeed be selecting a random value for each row in order to sort by it…

Tags:
  1. Alex Le
    April 3rd, 2006 at 14:46 | #1

    thanks for the tip,

    I am in a similar situation where I have to insert random values to a column of a table. Thanks for confirming this Update/Random in MySQL

  2. Adil
    April 10th, 2009 at 20:48 | #2

    I want to update a primary key with a random number, but I also want to ensure the new random number is also updated in the other table where that column is the foreign key.