Get a random value between two values in MySQL?

MySQLMySQLi Database

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. The maximum value we are considering is 200 and minimum is 100. The random number will be between 100 and 200 including 100 and 200 itself.

The query is as follows.

mysql> select FLOOR( RAND() * (200-100) + 100) as RandomValue;

The following is the output.

+-------------+
| RandomValue |
+-------------+
| 144         |
+-------------+
1 row in set (0.00 sec)

Now if we will run the same query again, the output will differ.

mysql> select FLOOR( RAND() * (200-100) + 100) as RandomValue;

The following is the output with a different value since these are random values between a range we set above.

+-------------+
| RandomValue |
+-------------+
| 184         |
+-------------+
1 row in set (0.00 sec)
raja
Published on 11-Jan-2019 11:08:37
Advertisements