Sort in a string mixed with numbers in MySQL?


Use ORDER BY with some cases. Let us create a table −

mysql> create table demo18
−> (
−> value text
−> );
Query OK, 0 rows affected (1.18 sec)

Insert some records into the table with the help of insert command −

mysql> insert into demo18 values('John Smith');
Query OK, 1 row affected (0.06 sec)

mysql> insert into demo18 values('2J John has 58');
Query OK, 1 row affected (0.17 sec)

mysql> insert into demo18 values('2J John has 9');
Query OK, 1 row affected (0.09 sec)

Display records from the table using select statement −

mysql> select *from demo18;

This will produce the following output −

+----------------+
| value          |
+----------------+
| John Smith     |
| 2J John has 58 |
| 2J John has 9  |
+----------------+
3 rows in set (0.00 sec)

Following is the query to sort −

mysql> select *from demo18
−> order by regexp_replace(value, '[0&minus9]*$', ''),
−> length(value),
−> value;

This will produce the following output −

+----------------+
| value          |
+----------------+
| 2J John has 9  |
| 2J John has 58 |
| John Smith     |
+----------------+
3 rows in set (0.14 sec)

Updated on: 19-Nov-2020

555 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements