Implement Custom Sort Order in MySQL

MySQLMySQLi Database

To implement custom sort order in MySQL, you need to use ORDER BY FIELD(). Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Designation varchar(100)
   -> );
Query OK, 0 rows affected (1.65 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Software Engineer');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Associate Software Engineer');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values('Software Development Engineer');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Product Manager');
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 −

+-------------------------------+
| Designation                   |
+-------------------------------+
| Software Engineer             |
| Associate Software Engineer   |
| Software Development Engineer |
| Product Manager               |
+-------------------------------+
4 rows in set (0.00 sec)

Following is the query to implement custom sort order in MySQL −

mysql> select *from DemoTable
   -> order by
field(Designation,'Associate Software Engineer','Software Engineer','Software Development Engineer','Product Manager');

This will produce the following output −

+-------------------------------+
| Designation                   |
+-------------------------------+
| Associate Software Engineer   |
| Software Engineer             |
| Software Development Engineer |
| Product Manager               |
+-------------------------------+
4 rows in set (0.02 sec)
raja
Published on 13-Dec-2019 05:36:38
Advertisements