Order by numeric value from string records separated by numbers like CSE 15, CSE 11, etc.?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable1969
   (
   BranchCode varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1969 values('CSE 101');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1969 values('CSE 11');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1969 values('CSE 15');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1969 values('CSE 6');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1969 values('CSE 201');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1969 values('CSE 110');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1969;

This will produce the following output −

+------------+
| BranchCode |
+------------+
| CSE 101    |
| CSE 11     |
| CSE 15     |
| CSE 6      |
| CSE 201    |
| CSE 110    |
+------------+
6 rows in set (0.00 sec)

Here is the query to order by numeric value from string records separated by numbers −

mysql> select * from DemoTable1969
   order by CAST(SUBSTRING(BranchCode,LOCATE(' ',BranchCode)+1) AS SIGNED) DESC;

This will produce the following output −

+------------+
| BranchCode |
+------------+
| CSE 201    |
| CSE 110    |
| CSE 101    |
| CSE 15     |
| CSE 11     |
| CSE 6      |
+------------+
6 rows in set (0.00 sec)
raja
Published on 31-Dec-2019 12:14:18
Advertisements