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)