Selecting Random Result from MySQL?


You need to use rand() function to select random result from MySQL.

The syntax is as follows

select *from yourTableName order by rand() limit 1;

To understand the above syntax, let us create a table. The query to create a table is as follows

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

Insert some records in the table using insert command.

The query is as follows

mysql> insert into selectRandomRecord(StudentName) values('John');
Query OK, 1 row affected (0.17 sec)
mysql> insert into selectRandomRecord(StudentName) values('Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into selectRandomRecord(StudentName) values('Bob');
Query OK, 1 row affected (0.12 sec)
mysql> insert into selectRandomRecord(StudentName) values('Sam');
Query OK, 1 row affected (0.15 sec)
mysql> insert into selectRandomRecord(StudentName) values('Mike');
Query OK, 1 row affected (0.16 sec)
mysql> insert into selectRandomRecord(StudentName) values('Robert');
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from selectRandomRecord;

The following is the output

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

The following is the query to select random result from MySQL.

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

The following is the output

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 3         | Bob         |
+-----------+-------------+
1 row in set (0.00 sec)

Now execute the same query again to get another random value

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

The following is the output

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 5         | Mike        |
+-----------+-------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements