0

I am using a Query which sorts like;

1
2
3A
3
4A
4

But I want to get it

1
2
3
3A
4
4A

What I am using is

SELECT * FROM `sections` ORDER BY CAST(`act` as DECIMAL) ASC

What I exactly want is First Number then Alphanumeric

3 then 3A
7
  • Otherfield ?? Otherfield will be written same or again act Commented Oct 19, 2020 at 3:41
  • Yes it is Only 1 Column Commented Oct 19, 2020 at 3:43
  • It's called natural sorting, mysql does not support this type of sorting, you can use php's natsort() to achieve that. Commented Oct 19, 2020 at 3:49
  • what is the datatype for act anyway? normal order by works fine sqlfiddle.com/#!9/50fb55/1 Commented Oct 19, 2020 at 3:50
  • the datatype is varchar for act because some time it has only numeric and some time alphanumeric Commented Oct 19, 2020 at 3:58

1 Answer 1

1

Considering that you'll always have integer first and then characters in your acts column. Normally this is called Natural Sorting.

Problem Understanding:

  • Normal sorting works perfectly when we're dealing with variations of a single number i.e. 1, 1A, 1B, 1AB...
  • Due to string type, it fails when we sort between numbers which starts with same digit like 1, 10, 100....

We can sort in following manner.

  • First sort them based on their integer values.
  • Then sort them normally which mysql takes care by default.
SELECT * FROM sections
ORDER BY CAST(acts AS UNSIGNED), acts

Check corresponding fiddle. It is working for MySQL 5.5, 5.6, 5.7 & 8.0.

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

Comments

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.