![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements