Home >Database >Mysql Tutorial >How to Sort MySQL Rows Numerically Based on Textual Identifiers with Embedded Numbers?
Extracting Numeric Values from Textual Identifiers in MySQL
Sorting text-based columns with mixed numeric and non-numeric values can be challenging. A common scenario involves identifier columns using the "name-number" format. To prioritize numerical ordering, extracting the numeric component becomes essential.
To achieve this in a MySQL query, you can utilize the following approach:
SELECT field, CONVERT(SUBSTRING_INDEX(field, '-', -1), UNSIGNED INTEGER) AS num FROM table ORDER BY num;
This query performs the following steps:
This approach is reliable even if the name part of the identifier does not contain any numbers. It effectively separates the numeric component and enables the sorting desired. By extracting and converting the numeric portion, you can accurately order the rows according to their numeric values, regardless of the character order of the overall identifiers.
The above is the detailed content of How to Sort MySQL Rows Numerically Based on Textual Identifiers with Embedded Numbers?. For more information, please follow other related articles on the PHP Chinese website!