How to select a random record from a MySQL database?



For this, you can use ORDER BY RAND LIMIT. Let us first create a table −

mysql> create table DemoTable1581
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20)
   -> );
Query OK, 0 rows affected (1.34 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1581(StudentName) values('Chris');
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable1581(StudentName) values('Bob');
Query OK, 1 row affected (1.58 sec)
mysql> insert into DemoTable1581(StudentName) values('Sam');
Query OK, 1 row affected (2.11 sec)
mysql> insert into DemoTable1581(StudentName) values('Mike');
Query OK, 1 row affected (0.55 sec)
mysql> insert into DemoTable1581(StudentName) values('Carol');
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1581;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         1 | Chris       |
|         2 | Bob         |
|         3 | Sam         |
|         4 | Mike        |
|         5 | Carol       |
+-----------+-------------+
5 rows in set (0.00 sec)

Here is the query to select a random record from a MySQL database −

mysql> select * from DemoTable1581 order by rand() limit 1;

This will produce the following output −

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|         4 | Mike        |
+-----------+-------------+
1 row in set (0.07 sec)

Advertisements