Syntax error Sort only numbers from alphanumeric string in MySQL?

Sort only numbers from alphanumeric string in MySQL?



To sort only numbers from alphanumeric string, use ORDER BY RIGHT(). Let us first create a table −

mysql> create table DemoTable1948
   (
   StudentCode varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1948 values('121John_567');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1948 values('Adam_101');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1948 values('Bob_563');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1948 values('Sam_346');
Query OK, 1 row affected (0.00 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1948;

This will produce the following output −

+-------------+
| StudentCode |
+-------------+
| 121John_567 |
| Adam_101    |
| Bob_563     |
| Sam_346     |
+-------------+
4 rows in set (0.00 sec)

Here is the query to sort only numbers from alphanumeric string in MySQL −

mysql> select * from DemoTable1948
   order by RIGHT(StudentCode,3);

This will produce the following output −

+-------------+
| StudentCode |
+-------------+
| Adam_101    |
| Sam_346     |
| Bob_563     |
| 121John_567 |
+-------------+
4 rows in set (0.00 sec)
Updated on: 2019-12-31T06:45:01+05:30

323 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements