Inserting random numbers into a table in MySQL?


To insert random numbers, use RAND() function from MySQL. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.08 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
|    10 |
|    20 |
|    30 |
+-------+
3 rows in set (0.00 sec)

Let us insert random numbers into a table in MySQL −

mysql> update DemoTable set Value=FLOOR(@number * rand()) + 1;
Query OK, 3 rows affected (0.17 sec)
Rows matched: 3 Changed: 3 Warnings: 0

Let us check table records once again −

mysql> select *from DemoTable;

This will produce the following output −

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

Updated on: 24-Sep-2019

756 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements