MySQL query to perform sort order on same field


For this, use ORDER BY IF().

Let us first create a table −

mysql> create table DemoTable801 (
 Score int
);
Query OK, 0 rows affected (0.69 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable801 values(30);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable801 values(99);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable801 values(45);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable801 values(55);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable801 values(99);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable801 values(69);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable801 values(25);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable801 values(79);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable801;

This will produce the following output -

+-------+
| Score |
+-------+
| 30    |
| 99    |
| 45    |
| 55    |
| 99    |
| 69    |
| 25    |
| 79    |
+-------+
8 rows in set (0.00 sec)

Following is the query to perform sort order on same field −

mysql> select *from DemoTable801 order by if(Score=99,1,0), Score;

This will produce the following output -

+-------+
| Score |
+-------+
| 25    |
| 30    |
| 45    |
| 55    |
| 69    |
| 79    |
| 99    |
| 99    |
+-------+
8 rows in set (0.00 sec)

Updated on: 09-Sep-2019

93 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements