Reorder integer except for value 0 with MySQL?

MySQLMySQLi Database

To reorder integer except for value 0, use the below syntax −

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

Let us first create a table −

mysql> create table reorderIntegerExcept0
   -> (
   -> value int
   -> );
Query OK, 0 rows affected (0.70 sec)

Following is the query to insert records in the table using insert command −

mysql> insert into reorderIntegerExcept0 values(90);
Query OK, 1 row affected (0.17 sec)

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

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

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

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

mysql> insert into reorderIntegerExcept0 values(50);
Query OK, 1 row affected (0.17 sec)

mysql> insert into reorderIntegerExcept0 values(80);
Query OK, 1 row affected (0.13 sec)

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

mysql> insert into reorderIntegerExcept0 values(300);
Query OK, 1 row affected (0.20 sec)

Following is the query to display all records from the table using select statement −

mysql> select * from reorderIntegerExcept0;

This will produce the following output −

+-------+
| value |
+-------+
| 90    |
| 10    |
| 0     |
| 40    |
| 0     |
| 50    |
| 80    |
| 0     |
| 300   |
+-------+
9 rows in set (0.00 sec)

Following is the query to reorder integer except for value 0 −

mysql> select * from reorderIntegerExcept0 order by value =0 ,value;

This will produce the following output −

+-------+
| value |
+-------+
| 10    |
| 40    |
| 50    |
| 80    |
| 90    |
| 300   |
| 0     |
| 0     |
| 0     |
+-------+
9 rows in set (0.00 sec)

If you want it in descending order for integers except 0, use the below query −

mysql> select * from reorderIntegerExcept0 order by value =0,value DESC;

This will produce the following output −

+-------+
| value |
+-------+
| 300   |
| 90    |
| 80    |
| 50    |
| 40    |
| 10    |
| 0     |
| 0     |
| 0     |
+-------+
9 rows in set (0.00 sec)
raja
Updated on 30-Jul-2019 22:30:25

Advertisements