- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
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)
Advertisements