- 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
Order by selected record in MySQL?
You can use a CASE statement for this. Let us first create a table −
mysql> create table DemoTable ( Number int ); Query OK, 0 rows affected (0.71 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values(490); Query OK, 1 row affected (0.35 sec) mysql> insert into DemoTable values(310); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(540); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(123); Query OK, 1 row affected (0.60 sec) mysql> insert into DemoTable values(1230); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(1090); Query OK, 1 row affected (0.43 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select * from DemoTable;
This will produce the following output −
+--------+ | Number | +--------+ | 490 | | 310 | | 540 | | 123 | | 1230 | | 1090 | +--------+ 6 rows in set (0.00 sec)
Following is the query to order by selected record in MySQL −
mysql> select *from DemoTable order by (case when Number = 1090 then 0 else 1 end), Number;
This will produce the following output −
+--------+ | Number | +--------+ | 1090 | | 123 | | 310 | | 490 | | 540 | | 1230 | +--------+ 6 rows in set (0.00 sec)
Advertisements