2
$\begingroup$

I have table like server(id,name,ip). When I'm trying to sort results by name, I get:

srv1,srv10,srv11,srv2,srv6

but I need the results like srv1,srv2,srv6,srv10,srv11

One idea I know is

ORDER BY LENGTH(name), name

but I have different lengths in name column

What do I need to do?

$\endgroup$
2
  • $\begingroup$ possible duplicate of Sorting string column containing numbers in SQL? $\endgroup$ Commented May 10, 2011 at 9:14
  • $\begingroup$ I was not found worked code for my issue in that question. $\endgroup$ Commented May 10, 2011 at 10:00

2 Answers 2

6
$\begingroup$

You could try this:

SELECT id,name,ip,CONVERT(SUBSTRING(name FROM 4),UNSIGNED INTEGER) num
ORDER BY num;
$\endgroup$
Sign up to request clarification or add additional context in comments.

Comments

1
$\begingroup$

Natural sorting is not implemented in MySQL. You should try a different approach. In this example I assume that the server name has always the same template (i.e. srv###).

select
    name, 
    mid(name, 4, LENGTH(name)-3) as num, 
    CAST(mid(name, 4, LENGTH(name)-3) AS unsigned) as parsed_num 
from server
order by parsed_num asc;

As I said, this approach is very specific, since you assume that the first 3 characters are to be ignored. This could be misleading and difficult to handle if you change the template.

You could chose to add a column to the table, let's call it prefix in which you set the prefix name for the server (in your example it will be srv for each one). Then you could use:

select
    name,
    prefix,
    mid(name, LENGTH(prefix) + 1, LENGTH(name)-LENGTH(prefix)) as num, 
    CAST(mid(name, LENGTH(prefix) + 1, LENGTH(name)-LENGTH(prefix)) AS unsigned) as parsed_num  
from server
order by parsed_num asc;

obtaining a more robust approach.

$\endgroup$

3 Comments

Thank you but I names has no single template (it may be host#, sw#, csw# etc.)
In that case you should add, for each server, the corresponding prefix in the column prefix, the use the order by prefix asc, parsed_num asc clause
If you put in the database different server names (as in host###, sw###, etc.) the previous answer solution will simply not work, because it will assume that the prefix will always be 3 characters long. Try the approach I suggested, then let me know if it works or not for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.