"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Sort String Columns with Embedded Numbers in SQL?

How to Sort String Columns with Embedded Numbers in SQL?

Published on 2024-11-10
Browse:572

How to Sort String Columns with Embedded Numbers in SQL?

Sorting String Columns with Embedded Numbers in SQL

In SQL, it is possible to sort string columns containing numbers using specific techniques. This can be useful when the natural sorting algorithm of databases like MySQL does not produce the desired results.

To achieve custom sorting of string columns with numbers, several approaches can be employed:

Using CAST and SUBSTRING:

SELECT *
FROM table
ORDER BY CAST(SUBSTRING(column,LOCATE(' ',column) 1) AS SIGNED)

This technique breaks down the column into two parts: the prefix before the space and the number after it. The number is then cast to a numeric type (in this case, SIGNED) for comparison.

Using SUBSTRING_INDEX:

ORDER BY SUBSTRING_INDEX(st, " ", 1) ASC, CAST(SUBSTRING_INDEX(st, " ", -1) AS SIGNED)

This approach uses the SUBSTRING_INDEX function to extract the prefix and number components. It then sorts first by the prefix and then by the converted number.

Note: If the column pattern differs from "WORD_space_NUMBER", a different approach may be necessary.

Examples:

Sample DataNatural SortingCustom Sorting
a 1, a 12, a 6, a 11a 1, a 12, a 2, a 3a 1, a 2, a 3, a 12
b 1, b 12, b 6, b 11b 1, b 12, b 2, b 3b 1, b 2, b 3, b 12

By employing these techniques, it is possible to sort string columns with embedded numbers in a customized manner, ensuring that the results align with specific application requirements.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3