How to place number 0 from a column at the end maintaining the ascending search order in MySQL?


Let us first create a table −

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

Insert some records in the table using insert command −

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

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

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

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

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

Display all records from the table using select statement −

mysql> select *from DemoTable

Output

This will produce the following output −

+--------+
| Number |
+--------+
|      9 |
|      4 |
|      0 |
|      7 |
|     11 |
+--------+
5 rows in set (0.00 sec)

Following is the query to use ORDER BY and place 0's at the end maintaining the ascending search order −

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

Output

This will produce the following output −

+--------+
| Number |
+--------+
| 4      |
| 7      |
| 9      |
| 11     |
| 0      |
+--------+
5 rows in set (0.00 sec)

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 30-Jun-2020

56 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements