- 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
Custom sorting using two different columns in MySQL?
For this, use ORDER BY clause along with CASE statement. Let us first create a table −
mysql> create table DemoTable1610 -> ( -> Marks int, -> Name varchar(20) -> ) ; Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1610 values(85,'John'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1610 values(78,'Carol'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1610 values(78,'John'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable1610 values(85,'Carol'); Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1610;
This will produce the following output
+-------+-------+ | Marks | Name | +-------+-------+ | 85 | John | | 78 | Carol | | 78 | John | | 85 | Carol | +-------+-------+ 4 rows in set (0.00 sec)
Here is the query to custom sort using two different columns in MySQL −
mysql> select * from DemoTable1610 -> order by Marks,case when Name='Carol' then 1 else 0 end;
This will produce the following output
+-------+-------+ | Marks | Name | +-------+-------+ | 78 | John | | 78 | Carol | | 85 | John | | 85 | Carol | +-------+-------+ 4 rows in set (0.00 sec)
- Related Articles
- Perform custom sorting in MySQL
- Count two different columns in a single query in MySQL?
- Set multiple values for custom columns in MySQL?
- Sorting a vector of custom objects using C++ STL
- How to move data between two tables with columns in different MySQL databases?
- Concatenate columns from different tables in MySQL
- Display two different columns from two different tables with ORDER BY?
- MySQL query to display custom text for empty columns
- Concatenate two columns in MySQL?
- How MySQL stored GENERATED COLUMNS are different from MySQL virtual GENERATED COLUMNS?
- Custom sorting in list of tuples in Python
- Count only null values in two different columns and display in one MySQL select statement?
- MySQL query for sorting on a columns partial value like number in “John_120 “
- Get MySQL maximum value from 3 different columns?
- MySQL query to calculate the days between two dates from different columns but similar rows

Advertisements