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;

Output

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;

Output

This will produce the following output −

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

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 30-Jun-2020

812 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements