0

I have a table which has three fields: "Id, Name, Sequence".
In the "Sequence" column there are the following entries: 1, 2, 3, 4, 2a, 5, 2b, 2c, 3, 4a (Row wise).

Now I want to a mysql query which can sort these values like:

1, 2, 2a, 2b, 2c, 3, 4, 4a, 5.

I have tried following query

SELECT * FROM table_name ORDER BY CAST(sequence AS UNSIGNED) ASC.
But it's not working.

9
  • you don't need anything but SELECT * FROM table_name ORDER BY sequence asc Commented Feb 20, 2018 at 17:07
  • @senape that will put 10 before 2 since the field is varchar not numeric. Commented Feb 20, 2018 at 17:08
  • @lurker you're right, I didn't think about it. actually, I tested with cast(sequence as unsigned) and it worked as expected. Commented Feb 20, 2018 at 17:12
  • @senape cast(sequence as unsigned) by itself doesn't work, either. It doesn't subsort 2, 2a, 2b for example. If your list has 2b, 2, 2a, then it leaves that order. Commented Feb 20, 2018 at 17:13
  • 1
    @senape, no it doesn't. See this example on SQL Fiddle. 3b comes before 3, but it shouldn't. Commented Feb 20, 2018 at 17:15

1 Answer 1

1

You want to order by the integer first, then order by the substring after the number by just ordering by the whole string as the sub-sort:

SELECT * FROM table_name ORDER BY CAST(sequence AS UNSIGNED), sequence;

Here's an SQL Fiddle with an example. I left off the ASC since that's the default.

Sign up to request clarification or add additional context in comments.

1 Comment

@VirendraPratapSingh that's great! If you could be so kind as to accept this answer by clicking the check mark next to it, I would appreciate it.

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.