- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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)
Advertisements