How to display 3 random values from MySQL table?

MySQLMySQLi Database

Use RAND() for random, whereas LIMIT 3 for the number of values i.e. 3 here −

select yourColumnName from yourTableName order by rand() limit 3;

Let us first create a table −

mysql> create table DemoTable646 (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,FirstName varchar(100)
);
Query OK, 0 rows affected (0.76 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable646(FirstName) values('John');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable646(FirstName) values('Bob');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable646(FirstName) values('Chris');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable646(FirstName) values('David');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable646(FirstName) values('Bob');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable646(FirstName) values('Carol');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable646(FirstName) values('Mike');
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable646;

This will produce the following output −

+----+-----------+
| Id | FirstName |
+----+-----------+
|  1 | John      |
|  2 | Bob       |
|  3 | Chris     |
|  4 | David     |
|  5 | Bob       |
|  6 | Carol     |
|  7 | Mike      |
+----+-----------+
7 rows in set (0.00 sec)

Following is the query to display 3 random values from MySQL table −

mysql> select FirstName from DemoTable646 order by rand() limit 3;

This will produce the following output −

+-----------+
| FirstName |
+-----------+
| Mike      |
| John      |
| Chris     |
+-----------+
3 rows in set (0.00 sec)
raja
Published on 23-Aug-2019 11:11:05
Advertisements