How to perform custom sort by field value in MySQL?


To perform custom sort by field value in MySQL, use the FIELD() method in ORDER BY. Let us first create a table:

mysql> create table DemoTable (StudentId int);
Query OK, 0 rows affected (0.58 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(110);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(90);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(70);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(120);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(140);
Query OK, 1 row affected (0.14 sec)

Following is the query to display records from the table using select command:

mysql> select *from DemoTable;

This will produce the following output:

+-----------+
| StudentId |
+-----------+
|       100 |
|       110 |
|        90 |
|        70 |
|       120 |
|       140 |
+-----------+
6 rows in set (0.00 sec)

Following is the query to perform custom MySQL sort by field value:

mysql> select *from DemoTable order by field(StudentId,'100','70','140','90','120','110');

This will produce the following output:

+-----------+
| StudentId |
+-----------+
|       100 |
|        70 |
|       140 |
|        90 |
|       120 |
|       110 |
+-----------+
6 rows in set (0.00 sec)

Updated on: 30-Jul-2019

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements