Implement MySQL ORDER BY without using ASC or DESC?

MySQLMySQLi Database

For this, you can use FIND_IN_SET(). Let us first create a table −

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

Insert some records in the table using insert command −

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

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

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

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

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+
| Number |
+--------+
|     20 |
|     60 |
|     40 |
|    800 |
+--------+
4 rows in set (0.00 sec)

Here is the query to implement MySQL ORDER BY without using ASC or DESC.

mysql> select *from DemoTable
   -> order by FIND_IN_SET(Number,'40,20,800,60');

This will produce the following output −

+--------+
| Number |
+--------+
|     40 |
|     20 |
|    800 |
|     60 |
+--------+
4 rows in set (0.14 sec)
raja
Published on 10-Jul-2019 09:13:40
Advertisements