Order by desc except a single value in MySQL


Use ORDER BY and set DESC to order by desc. However, to get all the values except a single value, use the not equal operator.

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.89 sec)

Insert some records in the table using insert command −

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

mysql> insert into DemoTable values('Chris');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.18 sec)

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

mysql> insert into DemoTable values('David');
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 −

+-------+
| Name  |
+-------+
| Sam   |
| Chris |
| John  |
| Carol |
| Adam  |
| David |
+-------+
6 rows in set (0.00 sec)

Following is the query to order by desc except a single value i.e. Name “Adam” here −

mysql> select *from DemoTable ORDER BY (Name <> 'Adam') DESC,Name;

This will produce the following output −

+-------+
| Name  |
+-------+
| Carol |
| Chris |
| David |
| John  |
| Sam   |
| Adam  |
+-------+
+6 rows in set (0.00 sec)
raja
Published on 12-Jul-2019 15:36:16
Advertisements