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)
raja
Published on 07-Oct-2019 15:38:27
Advertisements