MySQL query to first set negative value in descending order and then positive value in ascending order


For this, you can use UNION. Let us first create a table −

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

Insert some records in the table using insert command −

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

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

mysql> insert into DemoTable values(-9);
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable values(-190);
Query OK, 1 row affected (0.14 sec)

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

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

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

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+--------+
| Number |
+--------+
| 10     |
| 100    |
| -9     |
| -190   |
| 190    |
| 0      |
| 140    |
+--------+
7 rows in set (0.00 sec)

Following is the query to display negative value in descending order and then positive value in ascending order. Initially, we are displaying 0 −

mysql> (select *from DemoTable where Number=0)
-> union
-> (select *from DemoTable where Number < 0 order by Number desc)
-> union
-> (select *from DemoTable where Number > 0 order by Number);

output

This will produce the following output −

+--------+
| Number |
+--------+
| 0      |
| -9     |
| -190   |
| 10     |
| 100    |
| 190    |
| 140    |
+--------+
7 rows in set (0.03 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jun-2020

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements