Alphanumeric Order by in MySQL for strings mixed with numbers


Let’s say you have a VARCHAR column in a table with values are strings and the numbers are on the right side. For example −

John1023
Carol9871
David9098

Now, consider you want to order by on the basis of these right-side numbers in the entire column. For this, use ORDER BY RIGHT.

Let us first create a table −

mysql> create table DemoTable757 (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientId varchar(100)
);
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable757(ClientId) values('John1023');
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable757(ClientId) values('Carol9871');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable757(ClientId) values('David9098');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable757(ClientId) values('Adam9989');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable757(ClientId) values('Bob9789');
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable757;

This will produce the following output -

+----+-----------+
| Id | ClientId  |
+----+-----------+
|  1 | John1023  |
|  2 | Carol9871 |
|  3 | David9098 |
|  4 | Adam9989  |
|  5 | Bob9789   |
+----+-----------+
5 rows in set (0.00 sec)

Following is the query for alphanumeric order by in MySQL −

mysql> select Id,ClientId from DemoTable757 order by right(ClientId,4);

This will produce the following output -

+----+-----------+
| Id | ClientId  |
+----+-----------+
|  1 | John1023  |
|  3 | David9098 |
|  5 | Bob9789   |
|  2 | Carol9871 |
|  4 | Adam9989  |
+----+-----------+
5 rows in set (0.00 sec)

Updated on: 03-Sep-2019

430 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements