ORDER BY alphabet first then follow by number in MySQL?

MySQLMySQLi Database

You need to use regular expression with ORDER BY clause. The syntax is as follows:

SELECT *FROM yourTableName
ORDER BY IF(yourColumnName RLIKE '^[a-z]', 1, 2),yourColumnName;

To understand the above syntax, let us create a table. The query to create a table is as follows:

mysql> create table AlphabetFirstThenNumberDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.95 sec)

Insert some records in the table using insert command. The query is as follows:

mysql> insert into AlphabetFirstThenNumberDemo(Name) values('John');
Query OK, 1 row affected (0.37 sec)
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('Bob');
Query OK, 1 row affected (0.21 sec)
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('1Sam');
Query OK, 1 row affected (0.17 sec)
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('Carol');
Query OK, 1 row affected (0.22 sec)
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('2Larry');
Query OK, 1 row affected (0.31 sec)
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('David');
Query OK, 1 row affected (0.27 sec)
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('3Mike');
Query OK, 1 row affected (0.14 sec)
mysql> insert into AlphabetFirstThenNumberDemo(Name) values('Robert');
Query OK, 1 row affected (0.10 sec)

Now you can display all records from the table using select statement. The query is as follows:

mysql> select *from AlphabetFirstThenNumberDemo;

The following is the output:

+----+--------+
| Id | Name   |
+----+--------+
|  1 | John   |
|  2 | Bob    |
|  3 | 1Sam   |
|  4 | Carol  |
|  5 | 2Larry |
|  6 | David  |
|  7 | 3Mike  |
|  8 | Robert |
+----+--------+
8 rows in set (0.00 sec)

Here is the query order by alphabet first then followed by a number. The query is as follows:

mysql> select *from AlphabetFirstThenNumberDemo
   -> ORDER BY IF(Name RLIKE '^[a-z]', 1, 2),Name;

The following is the output:

+----+--------+
| Id | Name   |
+----+--------+
|  2 | Bob    |
|  4 | Carol  |
|  6 | David  |
|  1 | John   |
|  8 | Robert |
|  3 | 1Sam   |
|  5 | 2Larry |
|  7 | 3Mike  |
+----+--------+
8 rows in set (0.00 sec)
raja
Published on 27-Feb-2019 05:54:03
Advertisements