Select random number from a specific list in MySQL?


You can use elt() along with rand() for this. Let us select random number from a specific list.

mysql> SELECT ELT(FLOOR(RAND() * 10) + 1,
   100,200,300,400,500,600,700,800,900,1000) AS random_value_from_listOfValues;

This will produce the following output −

+--------------------------------+
| random_value_from_listOfValues |
+--------------------------------+
| 1000                           |
+--------------------------------+
1 row in set (0.00 sec)

Now we will run the query again to select random number from a specific list.

mysql> SELECT ELT(FLOOR(RAND() * 10) + 1,
   100,200,300,400,500,600,700,800,900,1000) AS random_value_from_listOfValues;

This will produce the following output. This would be different from the above output since we are displaying random numbers −

+--------------------------------+
| random_value_from_listOfValues |
+--------------------------------+
| 400                            |
+--------------------------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements