Syntax error MySQL ORDER BY with different ordering for some of the values as descending and others ascending?

MySQL ORDER BY with different ordering for some of the values as descending and others ascending?



You can use the field() for this. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(70);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(60);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(56);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(81);
Query OK, 1 row affected (0.44 sec)
mysql> insert into DemoTable values(85);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+-------+
| Value |
+-------+
| 10    |
| 70    |
| 60    |
| 56    |
| 81    |
| 85    |
+-------+
6 rows in set (0.00 sec)

Following is the query to ORDER BY specific 3 values as descending and rest of the as ascending order −

mysql> select *from DemoTable order by field(Value,60,70,81) desc;

Output

+-------+
| Value |
+-------+
| 81    |
| 70    |
| 60    |
| 10    |
| 56    |
| 85    |
+-------+
6 rows in set (0.00 sec)
Updated on: 2019-07-30T22:30:26+05:30

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements