MySQL query to sort by certain last string character?


For this, you can use the CASE statement. To sort, use the ORDER BY clause. Let us first create a table −

mysql> create table DemoTable
   -> (
   -> ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ClientName varchar(20)
   -> );
Query OK, 0 rows affected (0.54 sec)

Insert some records in the table using insert command. Some records have certain last string like -D, etc −

mysql> insert into DemoTable(ClientName) values('Mike');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(ClientName) values('John');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(ClientName) values('John-D');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(ClientName) values('John-Smith');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(ClientName) values('Mike-Smith');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(ClientName) values('Mike-D');
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----------+------------+
| ClientId | ClientName |
+----------+------------+
|        1 | Mike       |
|        2 | John       |
|        3 | John-D     |
|        4 | John-Smith |
|        5 | Mike-Smith |
|        6 | Mike-D     |
+----------+------------+
6 rows in set (0.00 sec)

Here is the query to sort by certain last string character −

mysql> select
   -> case
   -> when right(ClientName,length(ClientName)-instr(ClientName,'-')) = `ClientName` THEN ''
   -> else right(`ClientName`,length(`ClientName`)-INSTR(`ClientName`,'-'))
   -> end as `last`,
   -> `ClientName`
   -> from
   -> DemoTable
   -> ORDER BY
   -> `last`,`ClientName`;

This will produce the following output −

+-------+------------+
| last  | ClientName |
+-------+------------+
|       | John       |
|       | Mike       |
| D     | John-D     |
| D     | Mike-D     |
| Smith | John-Smith |
| Smith | Mike-Smith |
+-------+------------+
6 rows in set (0.00 sec)

Updated on: 12-Dec-2019

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements