To generate random numbers, use the ORDER BY RAND() function in MySQL. Let us first create a table −
mysql> create table DemoTable (Value int); Query OK, 0 rows affected (0.76 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(89); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(98); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.34 sec) mysql> insert into DemoTable values(78); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(75); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(76); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(74); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(99); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(101); Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-------+ | Value | +-------+ | 89 | | 98 | | 10 | | 78 | | 75 | | 76 | | 74 | | 99 | | 101 | +-------+ 9 rows in set (0.00 sec)
Following is the query to generate 5 random numbers in MySQL stored procedure −
mysql> DELIMITER // mysql> CREATE PROCEDURE generate_Random5Numbers() BEGIN SELECT GROUP_CONCAT(Value SEPARATOR '/') FROM ( SELECT Value FROM ( SELECT Value FROM DemoTable WHERE Value BETWEEN 10 AND 100 ORDER BY RAND() LIMIT 5) Ascending_Order ORDER BY Value) 5Values; END // Query OK, 0 rows affected (0.31 sec) mysql> DELIMITER ;
Call a stored procedure with the help of call command.
mysql> call generate_Random5Numbers();
This will produce the following output −
+-----------------------------------+ | GROUP_CONCAT(Value SEPARATOR '/') | +-----------------------------------+ | 89/74/78/99/10 | +-----------------------------------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.02 sec)