Syntax error MySQL ORDER BY 'ENUM' type value based on conditions

MySQL ORDER BY 'ENUM' type value based on conditions



For this, use ORDER BY CASE statement. Let us first create a table, wherein we have ENUM type column −

mysql> create table DemoTable1461
   -> (
   -> DeckOfCards ENUM('K','J','A','Q')
   -> );
Query OK, 0 rows affected (0.64 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1461 values('K');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1461 values('A');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1461 values('J');
Query OK, 1 row affected (0.44 sec)
mysql> insert into DemoTable1461 values('Q');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1461;

This will produce the following output −

+-------------+
| DeckOfCards |
+-------------+
| K           |
| A           |
| J           |
| Q           |
+-------------+
4 rows in set (0.00 sec)

Following is the query to order by ENUM type value −

mysql> select * from DemoTable1461
   -> order by
   -> case DeckOfCards when 'A' then 100
   -> when 'K' then 101
   -> when 'Q' then 102
   -> else 103
   -> end;

This will produce the following output −

+-------------+
| DeckOfCards |
+-------------+
| A           |
| K           |
| Q           |
| J           |
+-------------+
4 rows in set (0.00 sec)
Updated on: 2019-12-10T06:56:49+05:30

509 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements