How to order results of a query randomly & select random rows in MySQL?



To order results of a query randomly, use ORDER BY RAND(). The syntax is as follows −

select * from DemoTable1559 where yourColumnName IN(yourValue1,yourValue2,....N) order by rand() limit yourLimitValue;

Let us first create a table −

mysql> create table DemoTable1559    -> (    -> EmployeeId int,    -> EmployeeName varchar(20),    -> EmployeeAge int    -> ); Query OK, 0 rows affected (1.22 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1559 values(101,'Bob',28); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1559 values(102,'Robert',26); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1559 values(103,'Sam',25); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1559 values(104,'Mike',29); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1559 values(105,'John',34); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1559 values(106,'Carol',31); Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1559;

This will produce the following output −

+------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ |        101 | Bob          |          28 | |        102 | Robert       |          26 | |        103 | Sam          |          25 | |        104 | Mike         |          29 | |        105 | John         |          34 | |        106 | Carol        |          31 | +------------+--------------+-------------+ 6 rows in set (0.00 sec)

Following is the query to order results of a query randomly and select random rows −

mysql> select * from DemoTable1559 where EmployeeId IN(101,103,106) order by rand() limit 3;

This will produce the following output −

+------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ |        101 | Bob          |          28 | |        103 | Sam          |          25 | |        106 | Carol        |          31 | +------------+--------------+-------------+ 3 rows in set (0.00 sec)
Updated on: 2019-12-12T06:44:02+05:30

465 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements