ORDER BY rand() and keep them grouped in MySQL?


Let us first create a table −

mysql> create table DemoTable
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentMarks int
   -> );
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command. We have also inserted duplicate records −

mysql> insert into DemoTable(StudentMarks) values(98);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(StudentMarks) values(98);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(StudentMarks) values(78);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(StudentMarks) values(78);
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable(StudentMarks) values(45);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable(StudentMarks) values(56);
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+--------------+
| StudentId | StudentMarks |
+-----------+--------------+
| 1         | 98           |
| 2         | 98           |
| 3         | 78           |
| 4         | 78           |
| 5         | 45           |
| 6         | 56           |
+-----------+--------------+
6 rows in set (0.00 sec)

Following is the query to order by rand() keeping them grouped −

mysql> select *from DemoTable order by rand(StudentMarks*100*RAND());

This will produce the following output. Here, the marks 98 records remain grouped −

+-----------+--------------+
| StudentId | StudentMarks |
+-----------+--------------+
| 3         | 78           |
| 6         | 56           |
| 5         | 45           |
| 4         | 78           |
| 1         | 98           |
| 2         | 98           |
+-----------+--------------+
6 rows in set (0.00 sec)

Updated on: 11-Dec-2019

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements