How to get MySQL random integer range?

MySQLMySQLi Database

To get the random integer range, use the rand() function. The query to create a table −

mysql> create table RandomIntegerDemo
−> (
   −> Number int
−> );
Query OK, 0 rows affected (0.61 sec)

Inserting records into table. The query is as follows −

mysql> insert into RandomIntegerDemo values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14);
Query OK, 14 rows affected (0.14 sec)
Records: 14 Duplicates: 0 Warnings: 0

Now you can display all records with the help of select statement. The query is as follows −

mysql> select *from RandomIntegerDemo;

The following is the output displaying integers −

+--------+
| Number |
+--------+
| 1      |
| 2      |
| 3      |
| 4      |
| 5      |
| 6      |
| 7      |
| 8      |
| 9      |
| 10     |
| 11     |
| 12     |
| 13     |
| 14     |
+--------+
14 rows in set (0.00 sec)

The query to generate the random integer range is as follows −

mysql> select Number, (FLOOR( 1 + RAND( ) *14 )) AS RandomValue
−> from RandomIntegerDemo
−> limit 0,14;

The output displays random integer range in the same table −

+--------+-------------+
| Number | RandomValue |
+--------+-------------+
|      1 | 9           |
|      2 | 8           |
|      3 | 13          |
|      4 | 13          |
|      5 | 10          |
|      6 | 10          |
|      7 | 7           |
|      8 | 3           |
|      9 | 8           |
|     10 | 2           |
|     11 | 14          |
|     12 | 6           |
|     13 | 3           |
|     14 | 9           |
+--------+-------------+
14 rows in set (0.00 sec)
raja
Updated on 29-Jun-2020 07:15:17

Advertisements