Sort character values from a column mixed with character and numbers in MySQL?


Let us first create a table −

mysql> create table DemoTable
   -> (
   -> Code varchar(20)
   -> );
Query OK, 0 rows affected (0.70 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('J23');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('C13');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('A61');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('D56');
Query OK, 1 row affected (0.11 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable;

This will produce the following output −

+------+
| Code |
+------+
| J23  |
| C13  |
| A61  |
| D56  |
+------+
4 rows in set (0.00 sec)

Here is the query to sort character values −

mysql> select * from DemoTable
   -> order by left(Code,1),
   -> cast(substr(Code, 2) as unsigned);

This will produce the following output −

+------+
| Code |
+------+
| A61  |
| C13  |
| D56  |
| J23  |
+------+
4 rows in set (0.05 sec)

Updated on: 26-Feb-2020

140 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements