MySQL ORDER BY with custom field value


To set custom field value, use FIND_IN_SET(). Let us first create a table −

mysql> create table DemoTable677(
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   UserStatus text
);
Query OK, 0 rows affected (1.07 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable677(UserStatus) values('BUSY');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable677(UserStatus) values('AT WORK');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable677(UserStatus) values('OFFLINE');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable677(UserStatus) values('BLOCKED');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable677;

This will produce the following output −

+--------+------------+
| UserId | UserStatus |
+--------+------------+
|      1 | BUSY       |
|      2 | AT WORK    |
|      3 | OFFLINE    |
|      4 | BLOCKED    |
+--------+------------+
4 rows in set (0.00 sec)

Following is the query to ORDER BY with custom field value −

mysql> select *from DemoTable677 ORDER BY FIND_IN_SET(UserStatus, 'BLOCKED,AT WORK,OFFLINE,BUSY');

This will produce the following output −

+--------+------------+
| UserId | UserStatus |
+--------+------------+
|      4 | BLOCKED    |
|      2 | AT WORK    |
|      3 | OFFLINE    |
|      1 | BUSY       |
+--------+------------+
4 rows in set (0.03 sec)

Updated on: 26-Aug-2019

279 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements