How to update MySQL column with random value?

MySQLMySQLi Database

To update column with random value, you can use the below syntax−

update yourTableName set yourColumnName =round(1+rand()*100);

The above syntax will generate a value between 1 to 100. Let us see an example and create a table−

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

Insert records in the table using insert command −

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(80);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(100000);
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable values(987);
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output−

+--------+
| Number |
+--------+
| 10     |
| 100    |
| 80     |
| 100000 |
| 987    |
+--------+
5 rows in set (0.00 sec)

Following is the query to update column with random value−

mysql> update DemoTable set Number=round(1+rand()*100);
Query OK, 5 rows affected (0.46 sec)
Rows matched: 5 Changed: 5 Warnings: 0

Let us display table records once again−

mysql> select *from DemoTable;

This will produce the following output −

+--------+
| Number |
+--------+
| 33     |
| 88     |
| 41     |
| 39     |
| 70     |
+--------+
5 rows in set (0.00 sec)
raja
Published on 03-May-2019 08:16:41
Advertisements