Order by on a specific number in MySQL?


Let us first create a table −

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

Insert some records in the table using insert command −

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

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

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

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

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

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

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+--------+
| status |
+--------+
| 30     |
| 20     |
| 20     |
| 30     |
| 10     |
| 40     |
+--------+
6 rows in set (0.00 sec)

Now, let’s say you want to use ORDER BY in a way to get the following result. Here, the number 10 is set in the end and rest of the list is ordered in ascending order.

20
20
30
30
40
10

Here is the query to implement order by clause on a specific number in MySQL.

mysql> select *from DemoTable order by status=10,status;

Output

+--------+
| status |
+--------+
| 20     |
| 20     |
| 30     |
| 30     |
| 40     |
| 10     |
+--------+
6 rows in set (0.00 sec)

Updated on: 30-Jul-2019

115 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements