MySQL order by field using CASE Statement

MySQLMySQLi Database

To order by field, use CASE statement. Let us first create a table −

mysql> create table DemoTable(StudentId varchar(100));
Query OK, 0 rows affected (1.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('STU-980');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable values('STU-1029');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable values('STU-189');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values('STU-890');
Query OK, 1 row affected (0.38 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-----------+
| StudentId |
+-----------+
| STU-980   |
| STU-1029  |
| STU-189   |
| STU-890   |
+-----------+
4 rows in set (0.00 sec)

Following is the query to MySQL order by field −

mysql> select *from DemoTable
   order by case WHEN StudentId = 'STU-890' THEN 1
   WHEN StudentId = 'STU-1029' THEN 2
   WHEN StudentId = 'STU-980' THEN 3
   WHEN StudentId = 'STU-189' THEN 4
   end;

This will produce the following output −

+-----------+
| StudentId |
+-----------+
| STU-890   |
| STU-1029  |
| STU-980   |
| STU-189   |
+-----------+
4 rows in set (0.08 sec)
raja
Published on 22-Aug-2019 11:17:21
Advertisements