
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MySQL Random Rows Sorted by Specific Column Name
Let us first create a table −
mysql> create table DemoTable1339 -> ( -> Name varchar(30), -> Score int -> ); Query OK, 0 rows affected (0.76 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1339 values('Chris',56); Query OK, 1 row affected (0.36 sec) mysql> insert into DemoTable1339 values('Bob',46); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1339 values('Adam',78); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1339 values('John',90); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable1339 values('Carol',98); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1339;
This will produce the following output −
+-------+-------+ | Name | Score | +-------+-------+ | Chris | 56 | | Bob | 46 | | Adam | 78 | | John | 90 | | Carol | 98 | +-------+-------+ 5 rows in set (0.00 sec)
Following is the query to sort random rows by NAME column −
mysql> select * from (select *from DemoTable1339 order by rand() limit 4) tbl order by Name;
This will produce the following output −
+-------+-------+ | Name | Score | +-------+-------+ | Adam | 78 | | Bob | 46 | | Carol | 98 | | Chris | 56 | +-------+-------+ 4 rows in set (0.05 sec)
Advertisements