How to order an alphanumeric column in MySQL?


To order an alphanumeric column with values like “100X, “2Z”, etc. use the ORDER BY. Let us first create a table −

mysql> create table DemoTable
-> (
-> StudentId varchar(100)
-> );
Query OK, 0 rows affected (0.52 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('2X');
Query OK, 1 row affected (0.21 sec)

mysql> insert into DemoTable values('100Y');
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values('100X');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable values('2Z');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable values('2Y');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable values('100Z');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

This will produce the following output −

+-----------+
| StudentId |
+-----------+
| 2X        |
| 100Y      |
| 100X      |
| 2Z        |
| 2Y        |
| 100Z      |
+-----------+
6 rows in set (0.00 sec)

Here is the query to order by an alphanumeric column in MySQL −

mysql>select *from DemoTable order by (StudentId+0), right(StudentId, 1);

Output

This will produce the following output −

+-----------+
| StudentId |
+-----------+
| 2X        |
| 2Y        |
| 2Z        |
| 100X      |
| 100Y      |
| 100Z      |
+-----------+
6 rows in set, 6 warnings (0.00 sec)

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 30-Jun-2020

874 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements