MySQL order by 0 first and then display the record in descending order?

MySQLMySQLi Database

In order to order by 0 first and then largest, you can use the below syntax −

select *from yourTableName order by yourColumnName=0 DESC,yourColumnName DESC;

Let us first create a table −

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

Insert records in the table using insert command −

mysql> insert into DemoTable values(90);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(0);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(20);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(0);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(70);
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable values(0);
Query OK, 1 row affected (0.15 sec)

Display records from the table using select command −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
| 90    |
| 0     |
| 20    |
| 0     |
| 10    |
| 70    |
| 0     |
+-------+
7 rows in set (0.00 sec)

Here is the query to order by 0 then display the largest element in DESC order −

mysql> select *from DemoTable order by Value=0 DESC,Value DESC;

This will produce the following output −

+-------+
| Value |
+-------+
| 0     |
| 0     |
| 0     |
| 90    |
| 70    |
| 20    |
| 10    |
+-------+
7 rows in set (0.00 sec)
raja
Published on 30-Apr-2019 06:49:26
Advertisements