MYSQL select a piece of a string and order by that piece

I would suggest that you look at the MySQL String Functions and more specifically the SUBSTRING_INDEX function. The reason I suggest this one over SUBSTRING is because the number before or after the slash might be more than a single number which would make the length of the first and/or second parts vary.

Example:

SELECT   `info`,
         SUBSTRING_INDEX(`info`, "https://stackoverflow.com/", 1) AS `first_part`,
         SUBSTRING_INDEX(`info`, "https://stackoverflow.com/", -1) AS `second_part`
FROM     `table`
ORDER BY `first_part` ASC,
         `second_part` ASC;

Result:

Result

Additional Example

In this example, I’m using CAST to convert the second part into an unsigned integer just in case it contains additional characters such as symbols or letters. In other words, the second part of “web-4/15.” would be “15” and the second part of “web-4/15****” would also be “15”.

SELECT   `info`,
          SUBSTRING_INDEX(`info`, "https://stackoverflow.com/", 1) AS `first_part`,
          CAST(SUBSTRING_INDEX(`info`, "https://stackoverflow.com/", -1) AS UNSIGNED) `second_part`
FROM     `table`
ORDER BY `first_part` ASC,
         `second_part` ASC;

Leave a Comment