![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MySQL ORDER BY with different ordering for some of the values as descending and others ascending?
You can use the field() for this. Let us first create a table −
mysql> create table DemoTable ( Value int ); Query OK, 0 rows affected (0.80 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(70); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(60); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(56); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable values(81); Query OK, 1 row affected (0.44 sec) mysql> insert into DemoTable values(85); Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
+-------+ | Value | +-------+ | 10 | | 70 | | 60 | | 56 | | 81 | | 85 | +-------+ 6 rows in set (0.00 sec)
Following is the query to ORDER BY specific 3 values as descending and rest of the as ascending order −
mysql> select *from DemoTable order by field(Value,60,70,81) desc;
Output
+-------+ | Value | +-------+ | 81 | | 70 | | 60 | | 10 | | 56 | | 85 | +-------+ 6 rows in set (0.00 sec)
Advertisements