Tutorialspoint

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


1 Answer
Sharon Christine

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

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;

This will produce the following output −

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

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.