How to generate 6-digit random number in MySQL?

MySQLMySQLi Database

You can use LPAD() along with rand() and floor() to generate 6-digit random number. Let us first create a table −

mysql> create table DemoTable
   (
   Value int
   );
Query OK, 0 rows affected (0.64 sec)

Insert records in the table using insert command −

mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(2);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(3);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(4);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(5);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(6);
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
| 1     |
| 2     |
| 3     |
| 4     |
| 5     |
| 6     |
+-------+
6 rows in set (0.00 sec)

Following is the query to generate 6-digit random number in MySQL −

mysql> update DemoTable
set Value=LPAD(FLOOR(RAND() * 999999.99), 6, '0');
Query OK, 6 rows affected (0.15 sec)
Rows matched: 6 Changed: 6 Warnings: 0

Let us display the updated records from the table −

mysql> select * from DemoTable;

This will produce the following output −

+--------+
| Value  |
+--------+
| 499540 |
| 550607 |
| 254419 |
| 620272 |
| 338104 |
| 829705 |
+--------+
6 rows in set (0.00 sec)
raja
Published on 03-May-2019 14:04:02
Advertisements