How do I create a random four-digit number in MySQL?


Let us first create a table −

mysql> create table DemoTable717 (
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserPassword int
);
Query OK, 0 rows affected (0.81 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable717(UserPassword) values(1454343);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable717(UserPassword) values(674654);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable717(UserPassword) values(989883);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable717(UserPassword) values(909983);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable717;

This will produce the following output -

+--------+--------------+
| UserId | UserPassword |
+--------+--------------+
| 1      | 1454343      |
| 2      | 674654       |
| 3      | 989883       |
| 4      | 909983       |
+--------+--------------+
4 rows in set (0.00 sec)

Following is the query to create a random 4 digit and set for the “UserPassword” column −

mysql> update DemoTable717
   SET UserPassword=(select floor(0+ RAND() * 10000));
Query OK, 4 rows affected (0.22 sec)
Rows matched: 4 Changed: 4 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable717;

This will produce the following output -

+--------+--------------+
| UserId | UserPassword |
+--------+--------------+
| 1      | 4319         |
| 2      | 3902         |
| 3      | 6553         |
| 4      | 1060         |
+--------+--------------+
4 rows in set (0.00 sec)

Updated on: 22-Aug-2019

638 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements