MySQL ORDER BY letters (not numbers) for column values comprising strings with numbers like '456 John Smith'


To ORDER BY letters, use ORDER BY SUBSTRING(). Let us first create a table −

mysql> create table DemoTable
(
   Id varchar(100)
);
Query OK, 0 rows affected (0.65 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('456 John Smith');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('897 Adam Smith');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('1009 Bob Smith');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----------------+
| Id             |
+----------------+
| 456 John Smith |
| 897 Adam Smith |
| 1009 Bob Smith |
+----------------+
3 rows in set (0.00 sec)

Following is the query to ORDER BY letters −

mysql> select *from DemoTable order by SUBSTRING(Id,LOCATE(' ', Id));

This will produce the following output −

+----------------+
| Id             |
+----------------+
| 897 Adam Smith |
| 1009 Bob Smith |
| 456 John Smith |
+----------------+
3 rows in set (0.05 sec)

Updated on: 25-Sep-2019

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements