How can we sort a query using ORDER BY CASE WHEN REGEXP?


Use regular expression along with CASE statement. Let us first create a table −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Value varchar(20)
   );
Query OK, 0 rows affected (0.66 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Value) values('101');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable(Value) values('P');
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable(Value) values('A');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable(Value) values('53');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(Value) values('R');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable(Value) values('C');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(Value) values('190');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+-------+
| Id | Value |
+----+-------+
| 1  | 101   |
| 2  | P     |
| 3  | A     |
| 4  | 53    |
| 5  | R     |
| 6  | C     |
| 7  | 190   |
+----+-------+
7 rows in set (0.00 sec)

Following is the query to sort a query with ORDER BY CASE −

mysql> SELECT Id, Value FROM DemoTable ORDER BY CASE
   WHEN Value REGEXP '[a-zA-Z]' THEN 0 ELSE 0+Value END ASC, Value;

This will produce the following output −

+----+-------+
| Id | Value |
+----+-------+
| 3  | A     |
| 6  | C     |
| 2  | P     |
| 5  | R     |
| 4  | 53    |
| 1  | 101   |
| 7  | 190   |
+----+-------+
7 rows in set (0.06 sec)

Updated on: 30-Jul-2019

416 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements