How can I use RAND() function in an ORDER BY clause to shuffle MySQL set of rows?


When we use MySQL ORDER BY clause with RAND() function then the result set would have the shuffled set of rows. In other words, the result set would be in a random order. To understand it considers a table ‘Employee’ having the following records −

mysql> Select * from employee;
+----+--------+--------+
| ID | Name   | Salary |
+----+--------+--------+
| 1  | Gaurav | 50000  |
| 2  | Rahul  | 20000  |
| 3  | Advik  | 25000  |
| 4  | Aarav  | 65000  |
| 5  | Ram    | 20000  |
| 6  | Mohan  | 30000  |
| 7  | Aryan  | NULL   |
| 8  | Vinay  | NULL   |
+----+--------+--------+
8 rows in set (0.00 sec)

Now, the query below will use ORDER BT RAND() to shuffle the set of rows in the result set −

mysql> Select * from Employee ORDER BY RAND();
+----+--------+--------+
| ID | Name   | Salary |
+----+--------+--------+
| 4  | Aarav  | 65000  |
| 1  | Gaurav | 50000  |
| 3  | Advik  | 25000  |
| 7  | Aryan  | NULL   |
| 6  | Mohan  | 30000  |
| 8  | Vinay  | NULL   |
| 5  | Ram    | 20000  |
| 2  | Rahul  | 20000  |
+----+--------+--------+
8 rows in set (0.00 sec)

Updated on: 20-Jun-2020

273 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements