Syntax error MySQL order by string with numbers?

MySQL order by string with numbers?



To MySQL order string with numbers, the following is the syntax, wherein we have used ORDER BY, SUBSTR() and CAST() −

SELECT *FROM yourTableName ORDER BY
SUBSTR(yourColumnName FROM 1 FOR 2),
CAST(SUBSTR(yourColumnName FROM 2) AS UNSIGNED);

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

mysql> create table OrderByStringWithNumbers
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Words varchar(10),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.86 sec)

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

mysql> insert into OrderByStringWithNumbers(Words) values('A10');
Query OK, 1 row affected (0.19 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A30');
Query OK, 1 row affected (0.19 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A12');
Query OK, 1 row affected (0.13 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A11');
Query OK, 1 row affected (0.17 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A28');
Query OK, 1 row affected (0.13 sec)

mysql> insert into OrderByStringWithNumbers(Words) values('A21');
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from OrderByStringWithNumbers;

The following is the output −

+----+-------+
| Id | Words |
+----+-------+
| 1  | A10   |
| 2  | A30   |
| 3  | A12   |
| 4  | A11   |
| 5  | A28   |
| 6  | A21   |
+----+-------+
6 rows in set (0.00 sec)

Here is the query to order by string with numbers −

mysql> select *from OrderByStringWithNumbers order by
   -> substr(Words from 1 for 2),
   -> cast(substr(Words from 2) AS UNSIGNED);

The following is the output −

+----+-------+
| Id | Words |
+----+-------+
| 1  | A10   |
| 4  | A11   |
| 3  | A12   |
| 6  | A21   |
| 5  | A28   |
| 2  | A30   |
+----+-------+
6 rows in set (0.00 sec)
Updated on: 2020-06-30T07:20:00+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements