
- Learn MySQL
- MySQL - Home
- MySQL - Introduction
- MySQL - Installation
- MySQL - Administration
- MySQL - PHP Syntax
- MySQL - Connection
- MySQL - Create Database
- MySQL - Drop Database
- MySQL - Select Database
- MySQL - Data Types
- MySQL - Create Tables
- MySQL - Drop Tables
- MySQL - Insert Query
- MySQL - Select Query
- MySQL - Where Clause
- MySQL - Update Query
- MySQL - Delete Query
- MySQL - Like Clause
- MySQL - Sorting Results
- MySQL - Using Join
- MySQL - NULL Values
- MySQL - Regexps
- MySQL - Transactions
- MySQL - Alter Command
- MySQL - Indexes
- MySQL - Temporary Tables
- MySQL - Clone Tables
- MySQL - Database Info
- MySQL - Using Sequences
- MySQL - Handling Duplicates
- MySQL - SQL Injection
- MySQL - Database Export
- MySQL - Database Import
Perform custom sorting in MySQL
To perform custom sorting in MySQL, use ORDER BY FIELD(). Let us first create a table −
mysql> create table DemoTable -> ( -> Id int -> ); Query OK, 0 rows affected (0.82 sec)
Insert some records in the table using insert command:
mysql> insert into DemoTable values(101); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values(103); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(102); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable values(105); Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+ | Id | +------+ | 101 | | 103 | | 102 | | 105 | +------+ 4 rows in set (0.00 sec)
Here is the query to perform custom sorting −
mysql> select *from DemoTable order by field(Id,102,105,101,103);
This will produce the following output −
+------+ | Id | +------+ | 102 | | 105 | | 101 | | 103 | +------+ 4 rows in set (0.00 sec)
- Related Articles
- Custom sorting using two different columns in MySQL?
- How to perform custom sort by field value in MySQL?
- Custom sorting in list of tuples in Python
- Sorting Custom Object by Implementing Comparable Interface in Java
- 8085 Program to perform sorting using bubble sort
- 8085 Program to perform sorting using selection sort
- C++ Program to Perform Sorting Using B-Tree
- Program to perform sorting using selection sort in 8085 Microprocessor
- Multiple column sorting in MySQL?
- Sorting a vector of custom objects using C++ STL
- Sorting varchar field numerically in MySQL?
- Sorting max to min value in MySQL
- Find lowest Date (custom) in MySQL?
- Implement Custom Sort Order in MySQL
- Perform NAND/NOR operations in MySQL

Advertisements