Sort a column in descending order after placing argument in MySQL IN()?


For this, use FIELD() function with DESC. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.27 sec)

mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable values(50);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+
| Number |
+--------+
|     10 |
|     20 |
|     30 |
|     40 |
|     50 |
+--------+
5 rows in set (0.00 sec)

Following is the query to sort a column in descending order after placing argument in MySQL IN() −

mysql> select *from DemoTable where Number IN (40,50,20,30,10) ORDER BY FIELD(Number, 40,50,20,30,10) DESC;

This will produce the following output −

+--------+
| Number |
+--------+
|     10 |
|     30 |
|     20 |
|     50 |
|     40 |
+--------+
5 rows in set (0.03 sec)
raja
Published on 12-Jul-2019 10:46:21
Advertisements