How to order and select query with conditions in MySQL?

MySQLMySQLi Database

Following is the syntax −

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

Let us first create a table −

mysql> create table DemoTable1348
   -> (
   -> Amount int
   -> );
Query OK, 0 rows affected (0.80 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1348 values(100);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1348 values(0);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1348 values(90);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1348 values(45);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1348 values(0);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1348 values(89);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1348;

This will produce the following output −

+--------+
| Amount |
+--------+
|    100 |
|      0 |
|     90 |
|     45 |
|      0 |
|     89 |
+--------+
6 rows in set (0.00 sec)

Following is the query to order and select query with conditions −

mysql> select * from DemoTable1348 order by Amount=0,Amount;

This will produce the following output −

+--------+
| Amount |
+--------+
|     45 |
|     89 |
|     90 |
|    100 |
|      0 |
|      0 |
+--------+
6 rows in set (0.00 sec)
raja
Published on 05-Nov-2019 13:55:38
Advertisements