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)

Updated on: 01-Oct-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements