0

In database, it store values are

M2345
45
M345
E21
A3 

is there a way to sort it correctly? like

A3
E21
45
M345
M2345
1
  • I've never seen this. It is sorted correctly, by ascii code. Without knowing if it exists or not, it would be chaos to do this with a replace at runtime. You could have a second column for sorting purposes that will expand the numeric value. You'd run into problems, meaning time-consuming literal programming, due to things like 4 = 'four', but 40 = 'forty' (not fourzero). Commented Oct 3, 2013 at 4:03

1 Answer 1

2

Assuming there can be at most one letter before the digits start, you could use a condition like this in your sorting definition:

ORDER BY CAST(IF(col REGEXP '^[a-z]', SUBSTRING(col, 2), col) AS SIGNED)

Unfortunately, MySQL doesn't have a replace function that can handle regular expressions, otherwise that would have been very helpful at this point.

You may also want to consider storing the numeric value itself in a separate calculated field for more efficient sorting.

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.