Skip to content
Advertisement

How to natural sort “X-Y” string data, first by X and then by Y?

Given this data:

I’ve tried several of the common natural sorting methods for mysql, but they won’t sort these in a natural descending way, like:

For example:

Advertisement

Answer

Assuming the parts on either side of the - are limited to 2 digits and 5 digits respectively, you can extract the two numeric values using SUBSTR (and LOCATE to find the - between the two numbers) and then LPAD to pad each of those values out to 2 and 5 digits to allow them to be sorted numerically:

Output (for my expanded sample):

Demo on db-fiddle

If the values can have more than 2 or 5 digits respectively, just change the second parameters to LPAD to suit.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement