Anubhav Singh
Anubhav Singh

Reputation: 482

How to sort varchar values MySQL

I have a table which has id's(varchar) as

-----------------------------------------
ID        |NAME    |COLUMN1  |COLUMN2   |
-----------------------------------------
11.10     |abcd    |New col  | new col  |
11.10(a)  |abcd    |New col  | New Col 2|
11.50     |abcd    |New COl  | New coli | 
11.50(a1) |abcd    |New col  | New Col 2|
11.50(a2) |abcd    |New col  | New Col 2|
11.300(a) |abcd    |New col  | New Col 2|
11.200(a) |abcd    |New col  | New Col 2|
11.100(a) |abcd    |New col  | New Col 2|
11.40(a)  |abcd    |New col  | New Col 2|

Now, if I am getting the sorted data using:

Select * from table order by length(id) asc,id;

I am getting result like

11.10
11.50
11.10(a)
11.100(a)
11.200(a)
11.300(a)
11.40(a)
11.50(a)
11.50(a1)

But I want the desired output as

11.10
11.10(a)
11.40(a)
11.50
11.50(a)
11.50(a2)
11.200(a)
11.300(a)

What would be the appropriate query for the same? I have tried it using CAST but I am getting the desired output.

Upvotes: 1

Views: 78

Answers (3)

Beck Rakhimov
Beck Rakhimov

Reputation: 45

Select Convert(Id,UNSIGNED INTEGER) AS num, col1, col2, col3 from Table Order By num This works as Oracle's To_Number, so I would suggest it will be useful

Upvotes: 0

Barbaros Özhan
Barbaros Özhan

Reputation: 65208

Your desired query maybe this one :

select ID           
  from Table_
 order by cast( SUBSTRING_INDEX(SUBSTRING_INDEX(id, '.',-1), '(', 1) as signed ),
                SUBSTRING_INDEX(SUBSTRING_INDEX(id, '(',-1), ')', 1);

SQL Fiddle Demo

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1269513

For your example, you can just use length():

order by length(id), id

A slightly more general approach uses substring_index() and implicit conversion:

order by substring_index(id, '.', 1) + 0,
         substring_index(id, '.', -1) + 0,
         id

Upvotes: 2

Related Questions