- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 FIELD with GROUP BY in a single MySQL query?
For this, let us first create a table −
mysql> create table DemoTable ( Message text ); Query OK, 0 rows affected (1.15 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Good'); Query OK, 1 row affected (0.43 sec) mysql> insert into DemoTable values('Bye'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values('Awesome'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values('Bye'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable values('Good'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values('Amazing'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Awesome'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('Bye'); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------+ | Message | +---------+ | Good | | Bye | | Awesome | | Bye | | Good | | Amazing | | Awesome | | Bye | +---------+ 8 rows in set (0.00 sec)
Following is the query to ORDER BY FIELD with GROUP BY in a single MySQL query −
mysql> select *from DemoTable group by Message order by field(Message,'Amazing','Awesome','Good','Bye');
This will produce the following output −
+---------+ | Message | +---------+ | Amazing | | Awesome | | Good | | Bye | +---------+ 4 rows in set (0.04 sec)
- Related Articles
- How to use ORDER BY field and sort by id in a single MySQL field?
- How to display records having sum between a specific range using GROUP BY, HAVING and ORDER BY in a single MySQL query?
- MySQL: update field with Group By?
- Order by a single field and display rest of the records in the same order with MySQL
- MySQL query to group rows by the numeric characters in a string field?
- Order by a function of two columns in a single MySQL query
- MySQL ORDER BY with custom field value
- Using GROUP BY and COUNT in a single MySQL query to group duplicate records and display corresponding max value
- A single MongoDB query to orderby date and group by user
- MySQL query to GROUP BY multiple columns
- MySQL IF/WHEN/ELSE/OR with ORDER BY FIELD
- How to use order by, group by in c#?
- MySQL query to order by NULL values
- How to order or choose rows in MySQL GROUP BY clause?
- Order by desc except a single value in MySQL

Advertisements