Question

I have a series of varchar fields in a MySQL database that are "numbered":

+-----------+
| name      |
+-----------+
|  thing 1  |
|  thing 2  |
|  thing 3  |
|  ...      |
|  thing 10 |
|  thing 11 |
+-----------+

I want to order them as listed above. However, a simple ORDER_BY table.name produces something like the following:

thing 1
thing 10
thing 11
thing 2
thing 3
...

This makes some sense, since MySQL is treating the entire field as a String (varchar). However, I've tried numerous methods to sort including CAST(name AS DECIMAL) and name + 0. This will only sort by the decimal part, ignoring the string part. None of these work because I need to sort by name first and then sort by the trailing decimal.

I tried ORDER_BY name, name + 0, but nothing seems to work. How do I perform and ORDER_BY and then ORDER_BY within that subset? (I think that will work).

Was it helpful?

Solution

You need to have two sorts - first by the name part, and second by the numeric part, like this:

order by left(name,instr(name,' ')),cast(right(name,instr(name,' ')+1) as decimal)

OTHER TIPS

The function SUBSTRING_INDEX can split the string.

SELECT SUBSTRING_INDEX(name, ' ', 1) AS a, CAST(SUBSTRING(name, ' ', -1) AS DECIMAL) AS b
FROM t
ORDER BY a, b
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top