MySQL query to order rows with value greater than zero?

MySQLMySQLi Database

Let us first create a table. Following is the query −

mysql> create table gettingAndOrderingRowsDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Value int
   -> );
Query OK, 0 rows affected (1.35 sec)

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

mysql> insert into gettingAndOrderingRowsDemo(Value) values(10);
Query OK, 1 row affected (0.33 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(13);
Query OK, 1 row affected (0.32 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(0);
Query OK, 1 row affected (0.17 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(20);
Query OK, 1 row affected (0.26 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(30);
Query OK, 1 row affected (0.50 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(60);
Query OK, 1 row affected (0.24 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(0);
Query OK, 1 row affected (0.28 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(45);
Query OK, 1 row affected (0.15 sec)

mysql> insert into gettingAndOrderingRowsDemo(Value) values(0);
Query OK, 1 row affected (0.69 sec)

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

mysql> select * from gettingAndOrderingRowsDemo;

This will produce the following output −

+----+-------+
| Id | Value |
+----+-------+
| 1  | 10    |
| 2  | 13    |
| 3  | 0     |
| 4  | 20    |
| 5  | 30    |
| 6  | 60    |
| 7  | 0     |
| 8  | 45    |
| 9  | 0     |
+----+-------+
9 rows in set (0.00 sec)

Following is the query to order with a value greater than zero −

mysql> select * from gettingAndOrderingRowsDemo
-> order by Value=0,Value;

This will produce the following output −

+----+-------+
| Id | Value |
+----+-------+
| 1  | 10    |
| 2  | 13    |
| 4  | 20    |
| 5  | 30    |
| 8  | 45    |
| 6  | 60    |
| 3  | 0     |
| 7  | 0     |
| 9  | 0     |
+----+-------+
9 rows in set (0.00 sec)
raja
Published on 15-Apr-2019 13:42:29
Advertisements