

- 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
Placing order according to the condition in MySQL?
For this, use ORDER BY CASE WHEN statement.
Let us create a table −
mysql> create table demo51 −> ( −> id int not null auto_increment primary key, −> name varchar(20) −> ); Query OK, 0 rows affected (1.08 sec)
Insert some records into the table with the help of insert command −
mysql> insert into demo51(name) values('John'); Query OK, 1 row affected (0.15 sec) mysql> insert into demo51(name) values('Bob'); Query OK, 1 row affected (0.09 sec) mysql> insert into demo51(name) values('David'); Query OK, 1 row affected (0.35 sec) mysql> insert into demo51(name) values('Sam'); Query OK, 1 row affected (0.14 sec)
Display records from the table using select statement −
mysql> select *from demo51;
This will produce the following output −
+----+-------+ | id | name | +----+-------+ | 1 | John | | 2 | Bob | | 3 | David | | 4 | Sam | +----+-------+ 4 rows in set (0.00 sec)
Following is the query to place order according to the condition −
mysql> select *from demo51 −> order by −> case when name="John" then 110 −> when name="Bob" then 105 −> when name="David" then 104 −> else 101 −> end;
This will produce the following output −
+----+-------+ | id | name | +----+-------+ | 4 | Sam | | 3 | David | | 2 | Bob | | 1 | John | +----+-------+ 4 rows in set (0.00 sec)
- Related Questions & Answers
- Sort a column in descending order after placing argument in MySQL IN()?
- ORDER BY records in MySQL based on a condition
- Python Pandas - Sort DataFrame in descending order according to the element frequency
- Python Pandas - Sort DataFrame in ascending order according to the element frequency
- Sort an array according to the order defined by another array in C++
- Check whether two strings are equivalent or not according to given condition in Python
- Correctly implement the AND condition in MySQL
- Sort the array of strings according to alphabetical order defined by another string in C++
- Avoid placing password on command line with MySQL Utilities?
- Truncate with condition in MySQL?
- Counting with condition in MySQL?
- Sum columns corresponding values according to similar dates in MySQL?
- MySQL command to order timestamp values in ascending order?
- MySQL UPDATE using IF condition
- Java Program to sort a list placing nulls in the end
Advertisements