- 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
MySQL ORDER BY with CASE WHEN
For this, you can use the ORDER BY CASE statement. Let us first create a table −
mysql> create table DemoTable order by with vas Color varchar(100) ); Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Red'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values('Green'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values('Blue'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values('Yellow'); Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+--------+ | Color | +--------+ | Red | | Green | | Blue | | Yellow | +--------+ 4 rows in set (0.00 sec)
Here is the query to order by with CASE WHEN −
mysql> select *from DemoTable order by case Color when 'Blue' then 10 when 'Green' then 20 when 'Yellow' then 30 else 100 end ;
This will produce the following output −
+--------+ | Color | +--------+ | Blue | | Green | | Yellow | | Red | +--------+ 4 rows in set (0.00 sec)
Advertisements