- 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
How to sort an alphanumeric column with different lengths in MySQL?
Let us first create a table −
mysql> create table DemoTable1623 -> ( -> StudentCode varchar(20) -> ); Query OK, 0 rows affected (0.47 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1623 values('STU-MIT-143'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1623 values('STU-MIT-10'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1623 values('STU-MIT-150'); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1623 values('STU-MIT-148'); Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1623;
This will produce the following output −
+-------------+ | StudentCode | +-------------+ | STU-MIT-143 | | STU-MIT-10 | | STU-MIT-150 | | STU-MIT-148 | +-------------+ 4 rows in set (0.00 sec)
Here is the query to sort an alphanumeric column with different lengths in MySQL.
mysql> select * from DemoTable1623 -> order by substring_index(StudentCode, '-', 1), -> substring_index(StudentCode, '-', -1) + 0;
This will produce the following output −
+-------------+ | StudentCode | +-------------+ | STU-MIT-10 | | STU-MIT-143 | | STU-MIT-148 | | STU-MIT-150 | +-------------+ 4 rows in set (0.00 sec)
Advertisements