It looks like RAND is what I need but I'm having a bit of trouble understanding how it works.
I need to insert a random number between 60 and 120 into a couple thousand rows. Table name is: listing and the column name is: hits
Could you please help?
Use RAND() : UPDATE videos SET likes = FLOOR(RAND()*(100-10+1)+10); Note that using FLOOR here is necessary, because the RAND() function generates a uniformly distributed floating point value between 0 and 1. Save this answer.
How do I insert a random number in a table in SQL? To create a random integer number between two values (range), you can use the following formula: SELECT FLOOR(RAND()*(b-a+1))+a; Where a is the smallest number and b is the largest number that you want to generate a random number for.
SQL RAND() example In the first example, we omit the seed, while in the second one, we specify the value (5) for the seed. SELECT RAND(); SELECT RAND(5); As you can see, in the first example, the RAND() function generates a random number in decimals between 0 to 1.
To get the random value between two values, use MySQL rand() method with floor(). The syntax is as follows. select FLOOR( RAND() * (maximumValue-minimumValue) + minimumValue) as anyVariableName; Let us check with some maximum and minimum value.
To make a random integer between 60 and 120, you need to do a bit of arithmetic with the results of RAND()
, which produces only floating point values:
SELECT FLOOR(60 + RAND() * 61);
So what's going on here:
RAND()
will produce a value like 0.847269199
. We multiply that by 61, which gives us the value 51.83615194. We add 60, since that's your desired offset above zero (111.83615194). FLOOR()
rounds the whole thing down to the nearest whole number. Finally, you have 111.
To do this over a few thousand existing rows:
UPDATE table SET randcolumn = FLOOR(60 + RAND() * 61) WHERE (<some condition if necessary>);
See the MySQL docs on RAND()
for more examples.
Note I think I have the arithmetic right, but if you get values of 59 or 121 outside the expected range, change the +60
up or down accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With