

- 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
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 Questions & Answers
- 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)?
- Sum of the series 1 + (1+2) + (1+2+3) + (1+2+3+4) + ... + (1+2+3+4+...+n) in C++
- Sum of the Series 1/(1*2) + 1/(2*3) + 1/(3*4) + 1/(4*5) + ... in C++\n
- Count number of trailing zeros in (1^1)*(2^2)*(3^3)*(4^4)*.. in C++
- Order by last 3 chars in MySQL?
- Program to find sum of series 1*2*3 + 2*3*4+ 3*4*5 + . . . + n*(n+1)*(n+2) in C++
- MySQL ORDER BY with custom field value
- How to ORDER BY last 2 character string in MySQL?
- C++ Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! + …… n/n!
- Python Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +…….+ n/n!
- Java Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +…….+ n/n!
- C++ Programe to find n-th term in series 1 2 2 3 3 3 4
- Program to find Sum of a Series a^1/1! + a^2/2! + a^3/3! + a^4/4! +…….+ a^n/n! in C++
Advertisements