- 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 specific field value first in MySQL
To order by specific field value first in MySQL, use ORDER BY FIELD(). Let us first create a table −
mysql> create table DemoTable849(Color varchar(100)); Query OK, 0 rows affected (0.56 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable849 values('RED'); Query OK, 1 row affected (0.33 sec) mysql> insert into DemoTable849 values('ORANGE'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable849 values('BLUE'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable849 values('GREEN'); Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable849;
This will produce the following output −
+--------+ | Color | +--------+ | RED | | ORANGE | | BLUE | | GREEN | +--------+ 4 rows in set (0.00 sec)
Following is the query to order by specific value first −
mysql> select *from DemoTable849 order by field(Color,'RED','GREEN','BLUE','ORANGE');
This will produce the following output −
+--------+ | Color | +--------+ | RED | | GREEN | | BLUE | | ORANGE | +--------+ 4 rows in set (0.00 sec)
Advertisements