- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to order by a custom rule like order like 4,2,1,3 in MySQL?
To order with a custom rule, use the ORDER BY FIELD(). Let us first create a table −
mysql> create table DemoTable ( Number int ); Query OK, 0 rows affected (0.55 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(1); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(4); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable values(2); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(3); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
Output
+--------+ | Number | +--------+ | 1 | | 4 | | 2 | | 3 | +--------+ 4 rows in set (0.00 sec)
Following is the query to ORDER BY custom rule, for example, 4,2,1,3 −
mysql> select *from DemoTable order by field(Number,4,2,1,3);
This will produce the following output with custom ordering −
+--------+ | Number | +--------+ | 4 | | 2 | | 1 | | 3 | +--------+ 4 rows in set (0.00 sec)
- Related Articles
- How to ORDER BY LIKE in MySQL?
- Multiple LIKE Operators with ORDER BY in MySQL?
- MySQL select order by acts like a string (not a number)?
- MySQL ORDER BY with custom field value
- Implement Custom Sort Order in MySQL
- MySQL query to ORDER BY `user_id` IN (1,2,3) AND `name` for custom ordering
- How to order by timestamp in MySQL?
- How to order by auto_increment in MySQL?
- How to ORDER BY RELEVANCE in MySQL?
- How to Order by a specific string in MySQL?
- MySQL ORDER BY letters (not numbers) for column values comprising strings with numbers like '456 John Smith'
- How to ORDER BY grouped fields in MySQL?
- Order by numeric value from string records separated by numbers like CSE 15, CSE 11, etc.?
- How to sort by value with MySQL ORDER BY?
- Implement ORDER BY in MySQL to order records in human readable format?

Advertisements