Home > Database > Mysql Tutorial > How to shuffle a MySQL rowset using the RAND() function in an ORDER BY clause?

How to shuffle a MySQL rowset using the RAND() function in an ORDER BY clause?

WBOY
Release: 2023-08-23 20:09:06
forward
1658 people have browsed it

如何在 ORDER BY 子句中使用 RAND() 函数来打乱 MySQL 行集?

When we use the MySQL ORDER BY clause with the RAND() function, the result set will have a shuffled set of rows. In other words, the result set will be in random order. To understand it, consider a table "Employee" with 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)
Copy after login

Now, the following query 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)
Copy after login

The above is the detailed content of How to shuffle a MySQL rowset using the RAND() function in an ORDER BY clause?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template