Set a certain value first with MySQL ORDER BY?

MySQLMySQLi Database

Let us first create a table −

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

Insert some records in the table using insert command −

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

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

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

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

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

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

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

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

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

mysql> insert into DemoTable values(98);
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 |
+--------+
| 10     |
| 20     |
| 12     |
| 14     |
| 19     |
| 45     |
| 56     |
| 103    |
| 87     |
| 98     |
+--------+
10 rows in set (0.00 sec)

Following is the query to order a certain value first with ORDER BY −

mysql− select *from DemoTable order by (Number=45) DESC,Number;

Output

This will produce the following output −

+--------+
| Number |
+--------+
| 45     |
| 10     |
| 12     |
| 14     |
| 19     |
| 20     |
| 56     |
| 87     |
| 98     |
| 103    |
+--------+
10 rows in set (0.00 sec)
raja
Published on 09-Jul-2019 14:29:22
Advertisements