MySQL query for sorting on a columns partial value like number in “John_120 “

MySQLMySQLi Database

For this, you can use SUBSTRING_INDEX() along with ORDER BY. Let us first create a table −

mysql> create table DemoTable1502
   -> (
   -> StudentId varchar(40)
   -> );
Query OK, 0 rows affected (0.54 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1502 values('John_120');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1502 values('John_201');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1502 values('Mike_178');
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable1502 values('Bob_198');
Query OK, 1 row affected (0.36 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1502;

This will produce the following output −

+-----------+
| StudentId |
+-----------+
| John_120  |
| John_201  |
| Mike_178  |
| Bob_198   |
+-----------+
4 rows in set (0.00 sec)

Following is the query to sort on columns partial value −

mysql> select substring_index(StudentId,'_',1) as LeftPart,
   -> substring_index(StudentId,'_',-1) as RightPart
   -> from DemoTable1502
   -> order by RightPart;

This will produce the following output −

+----------+-----------+
| LeftPart | RightPart |
+----------+-----------+
| John     |       120 |
| Mike     |       178 |
| Bob      |       198 |
| John     |       201 |
+----------+-----------+
4 rows in set (0.00 sec)
raja
Published on 11-Dec-2019 05:54:11
Advertisements