Wrap around to first value and implement MySQL ORDER BY ASC and DESC in a single query


Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.78 sec)
mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.94 sec)
mysql> insert into DemoTable values(30);
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values(90);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values(70);
Query OK, 1 row affected (0.49 sec)
mysql> insert into DemoTable values(80);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(9);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(8);
Query OK, 1 row affected (0.38 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable ;

This will produce the following output −

+-------+
| Value |
+-------+
|    20 |
|    40 |
|    30 |
|    10 |
|    90 |
|    70 |
|    80 |
|     9 |
|     8 |
+-------+
9 rows in set (0.00 sec)

Here is the query to wrap around” to the first value and implement ORDER BY ASC and DESC in a single query −

mysql> select *from DemoTable
   -> order by Value > 10 desc,Value asc;

This will produce the following output −

+-------+
| Value |
+-------+
|    20 |
|    30 |
|    40 |
|    70 |
|    80 |
|    90 |
|     8 |
|     9 |
|    10 |
+-------+
9 rows in set (0.00 sec)

Updated on: 13-Dec-2019

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements