

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 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)
- Related Questions & Answers
- ORDER BY specific field value first in MySQL
- How to perform custom sort by field value in MySQL?
- MySQL IF/WHEN/ELSE/OR with ORDER BY FIELD
- How to sort by value with MySQL ORDER BY?
- MySQL order by field using CASE Statement
- Set a certain value first with MySQL ORDER BY?
- How to ORDER BY FIELD with GROUP BY in a single MySQL query?
- MySQL Order by with case?
- Simulating MySQL's ORDER BY FIELD() in PostgreSQL?
- MySQL ORDER BY Date field not in date format?
- How to order by a custom rule like order like 4,2,1,3 in MySQL?
- How to use ORDER BY field and sort by id in a single MySQL field?
- MySQL: update field with Group By?
- MySQL order by string with numbers?
- MySQL ORDER BY with EXPLAIN command
Advertisements