Perform custom sorting in MySQL

MySQLMySQLi Database

To perform custom sorting in MySQL, use ORDER BY FIELD(). Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Id int
   -> );
Query OK, 0 rows affected (0.82 sec)

Insert some records in the table using insert command:

mysql> insert into DemoTable values(101);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(103);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(102);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values(105);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------+
|  Id  |
+------+
|  101 |
|  103 |
|  102 |
|  105 |
+------+
4 rows in set (0.00 sec)

Here is the query to perform custom sorting −

mysql> select *from DemoTable order by field(Id,102,105,101,103);

This will produce the following output −

+------+
| Id   |
+------+
|  102 |
|  105 |
|  101 |
|  103 |
+------+
4 rows in set (0.00 sec)
raja
Published on 18-Dec-2019 09:58:48
Advertisements