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…

2 thoughts on “MySQL and Random

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

Leave a Reply

Your email address will not be published. Required fields are marked *