- Trending Categories
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
How to ORDER BY grouped fields in MySQL?
To ORDER BY grouped fields, use ORDER BY CASE along with IN(). CASE evaluates different conditions whereas ORDER BY sort values in ascending or descending order. The MySQL IN() is used to find a match.
Let us first create a table −
mysql> create table DemoTable ( Value varchar(40) ); Query OK, 0 rows affected (0.52 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values('100&101'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values('Sam'); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values('90'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Mike45'); Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------+ | Value | +---------+ | John | | 100&101 | | Sam | | 90 | | Mike45 | +---------+ 5 rows in set (0.00 sec)
Following is the query to order by grouped field −
mysql> select *from DemoTable order by case when Value IN('John','Sam','Mike45') then 100 when Value='90' then 101 when Value='100&101' then 102 else 103 end;
This will produce the following output −
+---------+ | Value | +---------+ | John | | Sam | | Mike45 | | 90 | | 100&101 | +---------+ 5 rows in set (0.03 sec)
- Related Articles
- ORDER BY rand() and keep them grouped in MySQL?
- MySQL query to order by two fields and NULL values in chronological order?
- MongoDB order by two fields sum?
- How to ORDER BY RELEVANCE in MySQL?
- How to ORDER BY LIKE in MySQL?
- How to order by timestamp in MySQL?
- How to order by auto_increment in MySQL?
- MongoDB query for counting number of unique fields grouped by another field?
- Python – Descending Order Sort grouped Pandas dataframe by group size?
- Python – Ascending Order Sort grouped Pandas dataframe by group size?
- How to sort by value with MySQL ORDER BY?
- How to concatenate fields in MySQL?
- How to order by date and time in MySQL?
- How to Order by a specific string in MySQL?
- How to order MySQL rows by multiple columns?

Advertisements