0

I Have a Table which has a Column of Type 'varchar' of size 255 char. The sample values look like this

Test/16-17/1 Test/16-17/2 test/16-17/10 Test/16-17/11 Test/16-17/20 Test/16-17/22 

However on Using ORDER BY clause in the Select the Result is in following order

Test/16-17/1 Test/16-17/10 Test/16-17/11 Test/16-17/2 Test/16-17/20 Test/16-17/22 

How Do I get the Result in the Chronolgical Order of Numerical Values in the End of the values?

2
  • Which RDBMS are you using? Commented Jun 21, 2017 at 15:29
  • I am using MySQL Commented Jun 21, 2017 at 15:30

5 Answers 5

1

If it follows the same / and have 2 digits in the column, you can use

order by right(vtest,2) 
Sign up to request clarification or add additional context in comments.

1 Comment

Oh please test that
0
ORDER BY CONVERT( RIGHT( test_column_name, LENGTH(test_column_name) - LOCATE('/', REVERSE(test_column_name)) ), UNSIGNED INTEGER); 

OR

ORDER BY CONVERT(substring_index(id, '/', -1), UNSIGNED INTEGER); 

1 Comment

Yes sir, This 'ORDER BY CONVERT(substring_index(id, '/', -1), UNSIGNED INTEGER);' is working fanstastic as promising as it looks. This is a good generalized code. Thank You.
0

For your particular examples, you can order by length and then the value:

order by length(vtest), vtest 

I don't know if this will work for other rows not in the question.

Comments

0

This will work no matter what the first 10 characters are:

ORDER BY CONCAT(LEFT(vtest, 10), CASE WHEN LENGTH(vtest) = 12 THEN CONCAT(0,RIGHT(vtest,1)) ELSE RIGHT(vtest,2) END) 

Comments

0

Select the end part after the last "/", and then multiply it by 1 to convert it to a number:

ORDER BY RIGHT(test_column, LENGTH(test_column) - LOCATE('/', REVERSE(test_column))) * 1; 

OR

ORDER BY substring_index(id, '/', -1) * 1; 

This is basically the same as the answer by Keyur Panchal, but it uses implicit conversion which has several advantages: 1) Easier to read/write, 2) You don't need to worry about the type to convert to, 3) It ignores characters if they happen to exist in some values.

3 Comments

How is it not working? Did you get an error, or it didn't sort it the way you want? This is basically the same as the answer by Keyur Panchal, except it uses an implicit conversion instead of his explicit one. You said his answer worked, so mine must work too in the same manner. Implicit conversion offers many advantages.
If you like the substring_index better, then you can also use it with implicit conversion like this ORDER BY substring_index(id, '/', -1) * 1;.
'ORDER BY CONVERT(substring_index(amwp.amwplist.Work_ID_by_MoD, '/', -1), UNSIGNED INTEGER)' is working fantastic sir. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.