Select random number from a specific list in MySQL?

MySQLMySQLi Database

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)
raja
Published on 20-May-2019 08:49:15
Advertisements